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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值