Jeen 2016-11-04 11:30:18 6465次浏览 1条评论 4 0 0

原文来自: http://ydc.jeen.wang/article/view/id/2.html
转载请注明出处

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

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

配置篇

//config/db.php

return [
    'class' => 'yii\db\Connection',
//    'dsn' => 'mysql:host=127.0.0.1;dbname=test',
//    'username' => 'root',
//    'password' => 'root',
    'charset' => 'utf8',
    'tablePrefix' => 'test_',

    'masters' => [ //主库列表  配置单项
        ['dsn' => 'mysql:host=127.0.0.1;dbname=testmaster',],
    ],
    'masterConfig' => [ //主库通用配置
        'username' => 'root',
        'password' => 'root',
        'attributes' => [
            PDO::ATTR_TIMEOUT => 5
        ]
    ],
    'slaves' => [ //从库列表  配置单项
        ['dsn' => 'mysql:host=123.57.36.144;dbname=testslave',],
    ],
    'slaveConfig' => [ //从库通用配置
        'username' => 'root',
        'password' => 'root',
        'attributes' => [
            PDO::ATTR_TIMEOUT => 10
        ]
    ],
];

测试篇

//commands/HelloController.php 中补充以下action

    public function actionMasterSlaveTest()
    {
        //test_simple_data 测试表 包含 id  nickname  基础测试字段
        //包含一条测试数据    1    etSlave

        //测试一  模型 读写
        $slaveSeller = SimpleData::find()->where('`id`=1')->one();
        VarDumper::dump($slaveSeller->toArray());
        $slaveSeller->nickname = 'etMaster';
        if ($slaveSeller->save()) {
            //实例对象中的值已经更新, 不过实际写入的是主库
            VarDumper::dump($slaveSeller->toArray());
        } else {
            VarDumper::dump($slaveSeller->getErrors());
        }

        //测试二   SQL 读写一
        $db = \Yii::$app->getDb();
        $t = $db->createCommand('select * from test_simple_data where `id`=1')
            ->queryOne(); //正常从从库中读取
        VarDumper::dump($t);
        $rt = $db->createCommand()
            ->update('test_simple_data',['nickname'=>'update1'],['id'=>1])
            ->execute(); //正常写入主库
        VarDumper::dump($rt);

        //测试三  SQL 读写二
        $t = $db
            ->createCommand("update test_simple_data set nickname='update2' where `id`=1")
            ->execute();// 正常
        JHelper::echoln($t);
        $t = $db
            ->createCommand("update test_simple_data set nickname='update3' where `id`=1")
            ->query();// 错误,会在从库上执行
        VarDumper::dump($t);

    }

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

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

原文来自: http://ydc.jeen.wang/article/view/id/2.html
转载请注明出处

您需要登录后才可以评论。登录 | 立即注册