The content of this article is about laravel learning: the implementation of master-slave read-write separation configuration. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Find the following code in the connection factory of DB
.../vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php
/** * Get the read configuration for a read / write connection. * * @param array $config * @return array */ protected function getReadConfig(array $config) { $readConfig = $this->getReadWriteConfig($config, 'read'); return $this->mergeReadWriteConfig($config, $readConfig); } /** * Get a read / write level configuration. * * @param array $config * @param string $type * @return array */ protected function getReadWriteConfig(array $config, $type) { if (isset($config[$type][0])) { return $config[$type][array_rand($config[$type])]; } return $config[$type]; } /** * Merge a configuration for a read / write connection. * * @param array $config * @param array $merge * @return array */ protected function mergeReadWriteConfig(array $config, array $merge) { return array_except(array_merge($config, $merge), ['read', 'write']); }
The factory class performs reading operations by randomly obtaining the read DB configuration. From this, it can be concluded that the DB configuration should be as follows
'mysql' => [ 'write' => [ 'host' => '192.168.1.180', ], 'read' => [ ['host' => '192.168.1.182'], ['host' => '192.168.1.179'], ], 'driver' => 'mysql', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]
Enhanced version, supports multiple masters and multiple slaves, Supports independent user names and passwords. The configuration is as follows
'mysql' => [ 'write' => [ [ 'host' => '192.168.1.180', 'username' => '', 'password' => '', ], ], 'read' => [ [ 'host' => '192.168.1.182', 'username' => '', 'password' => '', ], [ 'host' => '192.168.1.179', 'username' => '', 'password' => '', ], ], 'driver' => 'mysql', 'database' => 'database', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]
Verification
Enable MySQL's general-log and monitor log changes through tail -f to determine whether the configuration is effective
Recommended related articles:
Functional testing of Laravel: test-driven development (with code)
The above is the detailed content of laravel learning: implementation of master-slave read-write separation configuration. For more information, please follow other related articles on the PHP Chinese website!