如何Yii2主从连接

时间:2022-12-23 21:07:59

I configured the MySQL master-slave replications.

我配置了MySQL主从复制。

How can I configure the Yii2 Active Record for insert,update and delete queries on master DB and read queries on slave DB's?

如何配置Yii2 Active Record以在主DB上插入,更新和删除查询以及在从DB上读取查询?

1 个解决方案

#1


Yii2 handles this automatically allowing you configure multiple slaves and even multiple masters.

Yii2自动处理此问题,允许您配置多个从站甚至多个主站。

[
    'class' => 'yii\db\Connection',

    // configuration for the master
    'dsn' => 'dsn for master server',
    'username' => 'master',
    'password' => '',

    // common configuration for slaves
    'slaveConfig' => [
        'username' => 'slave',
        'password' => '',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    // list of slave configurations
    'slaves' => [
        ['dsn' => 'dsn for slave server 1'],
        ['dsn' => 'dsn for slave server 2'],
        ['dsn' => 'dsn for slave server 3'],
        ['dsn' => 'dsn for slave server 4'],
    ],
]

Link to section in Yii2 Guide for more info: http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting

链接到Yii2指南中的部分了解更多信息:http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting

#1


Yii2 handles this automatically allowing you configure multiple slaves and even multiple masters.

Yii2自动处理此问题,允许您配置多个从站甚至多个主站。

[
    'class' => 'yii\db\Connection',

    // configuration for the master
    'dsn' => 'dsn for master server',
    'username' => 'master',
    'password' => '',

    // common configuration for slaves
    'slaveConfig' => [
        'username' => 'slave',
        'password' => '',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    // list of slave configurations
    'slaves' => [
        ['dsn' => 'dsn for slave server 1'],
        ['dsn' => 'dsn for slave server 2'],
        ['dsn' => 'dsn for slave server 3'],
        ['dsn' => 'dsn for slave server 4'],
    ],
]

Link to section in Yii2 Guide for more info: http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting

链接到Yii2指南中的部分了解更多信息:http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting