zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

PHP配置 读写 分离 主从
2023-09-14 08:57:58 时间

在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 使用数据库的并发问题 在秒杀,抢购等并发场景下,可能会出现超卖的现象; 如:我们一共只有100个商品,在最后一刻,我们已经消耗了99个商品,仅剩最后一个。这个时候,系统发来多个并发请求,这批请求读取到的商品余量都是1个,然后都通过了这一个余量判断,最终导致超发。