本文所讲的就是MySQL分库和主从读写分离在Yii的配置和使用。
ModelConfig.php
Yii默认是不支持读写分离的,我们可以利用Yii的事件驱动模式来实现MySQL的读写分离。
Yii提供了一个强大的CActiveRecord数据库操作类,通过重写getDbConnection方法来实现数据库的切换,然后通过事件 beforeSave、beforeDelete、beforeFind 来实现读写服务器的切换,还需要两个配置文件dbconfig和modelconfig分别配置数据库主从服务器和model所对应的数据库名称,附代码
DBConfig.php
- <?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,
- ),
- ),
- ),
- );
- <?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