您现在的位置是:首页 > 文章详情

[PHP] Larval 主从读写分离配置

日期:2018-04-19点击:362

在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变化来确定配置是否生效

原文链接:https://yq.aliyun.com/articles/583484
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章