Yii2 MySql读写分离主从使用实例

Yii2 MySql实现读写分离, Master Slave 主从配置及使用实例

Yii2 MySql读写分离主从使用实例

这边只关注测试使用,关于主从配置或更多服务器相关的请自行充电
废话不多说了,源码样例如下
基于Yii2 basic 应用模板

配置篇

  1. //config/db.php
  2. return [
  3. 'class' => 'yii\db\Connection',
  4. // 'dsn' => 'mysql:host=127.0.0.1;dbname=test',
  5. // 'username' => 'root',
  6. // 'password' => 'root',
  7. 'charset' => 'utf8',
  8. 'tablePrefix' => 'test_',
  9. 'masters' => [ //主库列表 配置单项
  10. ['dsn' => 'mysql:host=127.0.0.1;dbname=testmaster',],
  11. ],
  12. 'masterConfig' => [ //主库通用配置
  13. 'username' => 'root',
  14. 'password' => 'root',
  15. 'attributes' => [
  16. PDO::ATTR_TIMEOUT => 5
  17. ]
  18. ],
  19. 'slaves' => [ //从库列表 配置单项
  20. ['dsn' => 'mysql:host=123.57.36.144;dbname=testslave',],
  21. ],
  22. 'slaveConfig' => [ //从库通用配置
  23. 'username' => 'root',
  24. 'password' => 'root',
  25. 'attributes' => [
  26. PDO::ATTR_TIMEOUT => 10
  27. ]
  28. ],
  29. ];

测试篇

  1. //commands/HelloController.php 中补充以下action
  2. public function actionMasterSlaveTest()
  3. {
  4. //test_simple_data 测试表 包含 id nickname 基础测试字段
  5. //包含一条测试数据 1 etSlave
  6. //测试一 模型 读写
  7. $slaveSeller = SimpleData::find()->where('`id`=1')->one();
  8. VarDumper::dump($slaveSeller->toArray());
  9. $slaveSeller->nickname = 'etMaster';
  10. if ($slaveSeller->save()) {
  11. //实例对象中的值已经更新, 不过实际写入的是主库
  12. VarDumper::dump($slaveSeller->toArray());
  13. } else {
  14. VarDumper::dump($slaveSeller->getErrors());
  15. }
  16. //测试二 SQL 读写一
  17. $db = \Yii::$app->getDb();
  18. $t = $db->createCommand('select * from test_simple_data where `id`=1')
  19. ->queryOne(); //正常从从库中读取
  20. VarDumper::dump($t);
  21. $rt = $db->createCommand()
  22. ->update('test_simple_data',['nickname'=>'update1'],['id'=>1])
  23. ->execute(); //正常写入主库
  24. VarDumper::dump($rt);
  25. //测试三 SQL 读写二
  26. $t = $db
  27. ->createCommand("update test_simple_data set nickname='update2' where `id`=1")
  28. ->execute();// 正常
  29. JHelper::echoln($t);
  30. $t = $db
  31. ->createCommand("update test_simple_data set nickname='update3' where `id`=1")
  32. ->query();// 错误,会在从库上执行
  33. VarDumper::dump($t);
  34. }

使用 php yii hello/master-slave-test 进行测试

  • 备注
    • 推荐阅读源码后结合自己的环境进行测试,如果需要直接使用源码,请注意修改相关的连接的参数,并补全相关类的调用
    • 测试过程中请注意观察数据库中的数据变化,已经输出的调试信息
    • 查看配置,可以发现是可以配置多主或多从的,这个没有实测,欢迎看官们测试讨论赐教 :)