OnlyPHP

实现MySQL多库和读写分离

前段时间为SNS产品做了架构设计,在程序框架方面做了不少相关的压力测试,最终选定了YiiFramework,至于为什么没选用公司内部的PHP框架,其实理由很充分,公司的框架虽然是“前辈”们辛苦的积累,但毕竟不够成熟,没有大型项目的历练,犹如一个涉世未深的年轻小伙。Yii作为一个颇有名气开源产品,必定有很多人在使用,意味着有一批人在维护,而且在这之前,我也使用Yii开发过大型项目,Yii的设计模式和它的易扩展特性足以堪当重任。

SNS同一般的社交产品不同的就是它最终要承受大并发和大数据量的考验,架构设计时就要考虑这些问题, web分布式、负载均衡、分布式文件存储、MySQL分布式或读写分离、NoSQL以及各种缓存,这些都是必不可少的应用方案,本文所讲的就是MySQL分库和主从读写分离在Yii的配置和使用。

Yii默认是不支持读写分离的,我们可以利用Yii的事件驱动模式来实现MySQL的读写分离。

Yii提供了一个强大的CActiveRecord数据库操作类,通过重写getDbConnection方法来实现数据库的切换,然后通过事件 beforeSave、beforeDelete、beforeFind 来实现读写服务器的切换,还需要两个配置文件dbconfig和modelconfig分别配置数据库主从服务器和model所对应的数据库名称,附代码

DBConfig.php

 

  1. <?php  
  2. return array(  
  3. ’passport’ => array(  
  4. ’write’ => array(  
  5. class’ => ‘CDbConnection’,  
  6. ’connectionString’ => ‘mysql:host=10.1.39.2;dbname=db1′,  
  7. ’emulatePrepare’ => true,  
  8. //’enableParamLogging’ => true,   
  9. ’enableProfiling’ => true,  
  10. ’username’ => ‘root’,  
  11. ’password’ => ”,  
  12. ’charset’ => ‘utf8′,  
  13. ‘schemaCachingDuration’=>3600,  
  14. ),  
  15. ’read’ => array(  
  16. array(  
  17. class’ => ‘CDbConnection’,  
  18. ’connectionString’ => ‘mysql:host=10.1.39.3;dbname=db1,  
  19. ’emulatePrepare’ => true,  
  20. //’enableParamLogging’ => true,   
  21. ’enableProfiling’ => true,  
  22. ’username’ => ‘root’,  
  23. ’password’ => ”,  
  24. ’charset’ => ‘utf8′,  
  25. ‘schemaCachingDuration’=>3600,  
  26. ),  
  27. array(  
  28. class’ => ‘CDbConnection’,  
  29. ’connectionString’ => ‘mysql:host=10.1.39.4;dbname=db3′,  
  30. ’emulatePrepare’ => true,  
  31. //’enableParamLogging’ => true,   
  32. ’enableProfiling’ => true,  
  33. ’username’ => ‘root’,  
  34. ’password’ => ”,  
  35. ’charset’ => ‘utf8′,  
  36. ‘schemaCachingDuration’=>3600,  
  37. ),  
  38. ),  
  39. ),  
  40. );  
<?php
return array(
’passport’ => array(
’write’ => array(
’class’ => ‘CDbConnection’,
’connectionString’ => ‘mysql:host=10.1.39.2;dbname=db1′,
’emulatePrepare’ => true,
//’enableParamLogging’ => true,
’enableProfiling’ => true,
’username’ => ‘root’,
’password’ => ”,
’charset’ => ‘utf8′,
‘schemaCachingDuration’=>3600,
),
’read’ => array(
array(
’class’ => ‘CDbConnection’,
’connectionString’ => ‘mysql:host=10.1.39.3;dbname=db1,
’emulatePrepare’ => true,
//’enableParamLogging’ => true,
’enableProfiling’ => true,
’username’ => ‘root’,
’password’ => ”,
’charset’ => ‘utf8′,
‘schemaCachingDuration’=>3600,
),
array(
’class’ => ‘CDbConnection’,
’connectionString’ => ‘mysql:host=10.1.39.4;dbname=db3′,
’emulatePrepare’ => true,
//’enableParamLogging’ => true,
’enableProfiling’ => true,
’username’ => ‘root’,
’password’ => ”,
’charset’ => ‘utf8′,
‘schemaCachingDuration’=>3600,
),
),
),
);


ModelConfig.php

 

 

 

  1. <?php  
  2. return array(  
  3.   
  4. //key为数据库名称,value为Model   
  5. ’passport’ => array(‘User’,'Post’),  
  6.   
  7. ‘microblog’ => array(‘…’),  
  8.   
  9. );  
  10.   
  11. ?>  
<?php
return array(

//key为数据库名称,value为Model
’passport’ => array(‘User’,'Post’),

‘microblog’ => array(‘…’),

);

?>


ActiveRecord.php

 

 

    1. /** 
    2. * 基于CActiveRecord类的封装,实现多库和主从读写分离 
    3. * 所有Model都必须继承些类. 
    4. * 
    5. * @author atao<lnbalife@126.com> 
    6. */  
    7. class ActiveRecord extends CActiveRecord  
    8. {  
    9. //model配置   
    10. public $modelConfig = ”;  
    11.   
    12. //数据库配置   
    13. public $dbConfig = ”;  
    14.   
    15. //定义一个多数据库集合   
    16. static $dataBase = array();  
    17.   
    18. //当前数据库名称   
    19. public $dbName = ”;  
    20.   
    21. //定义库类型(读或写)   
    22. public $dbType = ‘read’; //’read’ or ‘write’   
    23.   
    24. /** 
    25. * 在原有基础上添加了一个dbname参数 
    26. * @param string $scenario Model的应用场景 
    27. * @param string $dbname 数据库名称 
    28. */  
    29. public function __construct($scenario=’insert’, $dbname = ”)  
    30. {  
    31. if (!empty($dbname))  
    32. $this->dbName = $dbname;  
    33.   
    34. parent::__construct($scenario);  
    35. }  
    36.   
    37. /** 
    38. * 重写父类的getDbConnection方法 
    39. * 多库和主从都在这里切换 
    40. */  
    41. public function getDbConnection()  
    42. {  
    43. //如果指定的数据库对象存在则直接返回   
    44. if (self::$dataBase[$this->dbName]!==null)  
    45. return self::$dataBase[$this->dbName];  
    46.   
    47. if ($this->dbName == ‘db’){  
    48. self::$dataBase[$this->dbName] = Yii::app()->getDb();  
    49. }else{  
    50. $this->changeConn($this->dbType);  
    51. }  
    52.   
    53. if(self::$dataBase[$this->dbName] instanceof CDbConnection){  
    54. self::$dataBase[$this->dbName]->setActive(true);  
    55. return self::$dataBase[$this->dbName];  
    56. else  
    57. throw new CDbException(Yii::t(‘yii’,'Model requires a “db” CDbConnection application component.’));  
    58.   
    59. }  
    60.   
    61. /** 
    62. * 获取配置文件 
    63. * @param unknown_type $type 
    64. * @param unknown_type $key 
    65. */  
    66. private function getConfig($type=”modelConfig”,$key=”){  
    67. $config = Yii::app()->params[$type];  
    68. if($key)  
    69. $config = $config[$key];  
    70. return $config;  
    71. }  
    72.   
    73. /** 
    74. * 获取数据库名称 
    75. */  
    76. private function getDbName(){  
    77. if($this->dbName)  
    78. return $this->dbName;  
    79. $modelName = get_class($this->model());  
    80. $this->modelConfig = $this->getConfig(‘modelConfig’);  
    81. //获取model所对应的数据库名   
    82. if($this->modelConfig)foreach($this->modelConfig as $key=>$val){  
    83. if(in_array($modelName,$val)){  
    84. $dbName = $key;  
    85. break;  
    86. }  
    87. }  
    88. return $dbName;  
    89. }  
    90.   
    91. /** 
    92. * 切换数据库连接 
    93. * @param unknown_type $dbtype 
    94. */  
    95. protected function changeConn($dbtype = ‘read’){  
    96.   
    97. if($this->dbType == $dbtype && self::$dataBase[$this->dbName] !== null)  
    98. return self::$dataBase[$this->dbName];  
    99.   
    100. $this->dbName = $this->getDbName();  
    101.   
    102. if(Yii::app()->getComponent($this->dbName.’_’.$dbtype) !== null){  
    103. self::$dataBase[$this->dbName] = Yii::app()->getComponent($this->dbName.’_’.$dbtype);  
    104. return self::$dataBase[$this->dbName];  
    105. }  
    106.   
    107. $this->dbConfig = $this->getConfig(‘dbConfig’,$this->dbName);  
    108.   
    109. //跟据类型取对应的配置(从库是随机值)   
    110. if($dbtype == ‘write’){  
    111. $config = $this->dbConfig[$dbtype];  
    112. }else{  
    113. $slavekey = array_rand($this->dbConfig[$dbtype]);  
    114. $config = $this->dbConfig[$dbtype][$slavekey];  
    115. }  
    116.   
    117. //将数据库配置加到component中   
    118. if($dbComponent = Yii::createComponent($config)){  
    119. Yii::app()->setComponent($this->dbName.’_’.$dbtype,$dbComponent);  
    120. self::$dataBase[$this->dbName] = Yii::app()->getComponent($this->dbName.’_’.$dbtype);  
    121. $this->dbType = $dbtype;  
    122. return self::$dataBase[$this->dbName];  
    123. else  
    124. throw new CDbException(Yii::t(‘yii’,'Model requires a “changeConn” CDbConnection application component.’));  
    125. }  
    126.   
    127. /** 
    128. * 保存数据前选择 主 数据库 
    129. */  
    130. protected function beforeSave(){  
    131. parent::beforeSave();  
    132. $this->changeConn(‘write’);  
    133. return true;  
    134. }  
    135.   
    136. /** 
    137. * 删除数据前选择 主 数据库 
    138. */  
    139. protected function beforeDelete(){  
    140. parent::beforeDelete();  
    141. $this->changeConn(‘write’);  
    142. return true;  
    143. }  
    144.   
    145. /** 
    146. * 读取数据选择 从 数据库 
    147. */  
    148. protected function beforeFind(){  
    149. parent::beforeFind();  
    150. $this->changeConn(‘read’);  
    151. return true;  
    152. }  
    153.   
    154. /** 
    155. * 获取master库对象 
    156. */  
    157. public function dbWrite(){  
    158. return $this->changeConn(‘write’);  
    159. }  
    160.   
    161. /** 
    162. * 获取slave库对象 
    163. */  
    164. public function dbRead(){  
    165. return $this->changeConn(‘read’);  
    166. }  
    167. }  

posted on 2013-05-02 16:16  OnlyPHP  阅读(1062)  评论(0编辑  收藏  举报

导航