Home > Article > Backend Development > yii2 database reading and writing separation configuration, yii2 database reading and writing_PHP tutorial
Original link: Yii Chinese website (yii-china.com) - yii2 database read and write separation configuration
Introduction
Separating database read and write is the first optimization step to consider when a website encounters a performance bottleneck. So how does yii2 separate database read and write? This tutorial will introduce you to the read-write separation configuration of yii2 database.
Data synchronization between the two servers is a prerequisite for read-write separation, but this is not included in the yii2 read-write separation tutorial. The database read-write separation configuration of yii2 only implements reading and writing in the main database and querying in the slave database, then We first need to configure data synchronization between the master and slave servers. For details, view the linux database master-slave synchronization configuration
Configuration
After the master-slave server database synchronization is completed, we can start the read-write separation configuration of yii2. The official document also has this aspect, but it is not clear and there is no practical example. Soy Sauce will improve it here.
1. Open our database configuration file commonconfigmain-local.php and make the following configuration in the db attribute
'db' => [ 'class' => 'yii\db\Connection', // 配置主服务器 'dsn' => 'mysql:host=192.168.0.1;dbname=hyii2', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', // 配置从服务器 'slaveConfig' => [ 'username' => 'root', 'password' => 'root', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], 'charset' => 'utf8', ], // 配置从服务器组 'slaves' => [ ['dsn' => 'mysql:host=192.168.0.2;dbname=hyii2'], ], ],
The above configuration can realize the operation of reading and writing separation in yii2 database. It is very simple. Just one configuration is enough. The function of reading and writing separation is automatically completed by the background code. The caller does not need to care.
The above is just a configuration of 1 master and 1 slave. If you want one master and multiple slaves, or multiple masters and multiple slaves, please refer to this example and official documents to complete it.
Click here for more quality documents about yii2