1. 程式人生 > >Larval 主從讀寫分離配置

Larval 主從讀寫分離配置

在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']);}

工廠類通過隨機獲取讀DB配置來進行讀取操作,由此可推出DB的配置應該如下
'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' => '', ]

加強版,支援多主多從,支援獨立使用者名稱和密碼,配置如下
'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' => '', ]

驗證開啟MySQL的general-log,通過tail -f的方式監控log變化來確定配置是否生效
更多PHP相關技術請搜尋千鋒PHP,做真實的自己,用良心做教育。
網際網路+時代,時刻要保持學習,攜手千鋒PHP,Dream It Possible。