SOURCE Link: Yii Chinese network (yii-china.com)-YII2 database read and write separation configuration
Brief introduction
Database read/write separation is the first step to consider the optimization when the website encounters performance bottleneck, then how does YII2 do the database read and write separation? This section of the tutorial to give you a common YII2 database read and write separation configuration.
Two server data synchronization is a prerequisite for read and write separation, but this is not in the YII2 read and write separation tutorial, YII2 database Read and write separation configuration, only realized in the main library read and write, in the library query, then we first configure the master-slave server data synchronization. Read more about Linux database master-Slave synchronization configuration
Configuration
After the master-slave server database synchronization is complete, we can begin to yii2 the read-write separation configuration, the official also has this document, but said is not clear, there is no practical example, soy sauce June here to perfect.
1. Open our database configuration file common\config\main-local.php The following configuration in the DB attribute
' DB ' => [ ' class ' => ' Yii\db\connection ', // Configure Master server ' DSN ' => ' mysql:host= 192.168.0.1;dbname=hyii2 ', ' username ' => ' root ', ' Password ' => ' root ', ' charset ' => ' UTF8 ', // Configure from server ' Slaveconfig ' => [ ' username ' => ' root ', ' password ' => ' root ', ' Attributes ' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ' CharSet ' => ' UTF8 ', ], // Configure from server group ' slaves ' => [ [' DSN ' => ' Mysql:host=192.168.0.2;dbname=hyii2 '], ],],
As above configuration can realize the YII2 database read and write separation operation, very simple, as long as a configuration is OK, the function of read and write separation is automatically completed by the background code. Callers need not care.
Above is just a 1 master 1 from the configuration, if you want a master more from, or multi-master more from, refer to this example and official documents can be completed.
More about YII2 's Boutique documentation click here
YII2 database read/write separation configuration