错误范例
最近要配置laravel的读写分离,找了半天资料都是类似下面的这种形式。
'mysql' => array(
'read' => array(
'host' => '192.168.1.1',
'host' => '192.168.1.3',
),
'write' => array(
'host' => '196.168.1.2',
'host' => '192.168.1.4',
),
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
一个array配置两个相同的key也是醉了,而且各个网站都是这么写的,爬数据能不能走点心。
求根溯源
无奈只能扒代码
在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];
}
工厂类通过随机获取读DB配置来进行读取操作,由此可推出DB的配置应该如下
'mysql' => [
'driver' => 'mysql',
'write' => [
'host' => '192.168.1.180',
],
'read' => [
['host' => '192.168.1.182'],
['host' => '192.168.1.179'],
],
...
]
验证
开启MySQL的general-log,通过tail -f的方式监控log变化来确定配置是否生效。