yii2 framework mysql read-write separation configuration, understand in seconds!

1. Find the yii2-app-basic\config\db.php database configuration file and add this code

2.db.php code

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=tp',
    'username' => 'root',
    'password' => '你的密码',
    'charset' => 'utf8',

    'slaveConfig' => [
        'username' => 'root',
        'password' => '你的密码',
        'attributes' => [
            //use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,    // 请求超时时间
        ],
    ],
    // 配置从服务器组
    'slaves' => [
        [
            'dsn' => 'mysql:host=192.168.0.2;dbname=tp'
        ]
    ]

    // Schema cache options (for production environment)
    //'enableSchemaCache' => true,
    //'schemaCacheDuration' => 60,
    //'schemaCache' => 'cache',
];

Change the password to your own, just fill in the database information of the slave server, and the yii framework will automatically help you realize the separation of reading and writing.

Guess you like

Origin blog.csdn.net/zhunju0089/article/details/103527482