Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Yii2 master-slave connections

Tags:

php

mysql

yii2

I configured the MySQL master-slave replications.

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

like image 349
Burhan Çetin Avatar asked May 11 '15 14:05

Burhan Çetin


1 Answers

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

[
    '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

like image 86
Michael St Clair Avatar answered Nov 07 '22 21:11

Michael St Clair