thinkphp 的主从数据库 链接资源分析
一主一丛
主 —负责数据的 插入,更新,删除
从 —负责数据的查询
操作的时候 通过 返回不同的 数据库链接来进行操作
下面是他的链接操作的代码
参数 $master 是关键
thinkphp 把默认的配置 的 第一个 ip 当作是主库, 其他的都是从库
如果是查询操作的时候,参数传递过来的永远是false , 根据下面的代码 他会 取得不同的配置文件 ,确定到底是链接那个数据库
[php]
protected function multiConnect($master=false) {
static $_config = array();
if(empty($_config)) {
// 缓存分布式数据库配置解析
foreach ($this->config as $key=>$val){
$_config[$key] = explode(‘,’,$val);
}
}
// 数据库读写是否分离
if(C(‘DB_RW_SEPARATE’)){
// 主从式采用读写分离
if($master) // ————————————- 这个地方应该是关键
// 默认主服务器是连接第一个数据库配置
$r = 0;
else
// 读操作连接从服务器
$r = floor(mt_rand(1,count($_config['hostname'])-1)); // 每次随机连接的数据库
}else{
// 读写操作不区分服务器
$r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库
}
$db_config = array(
‘username’ => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
‘password’ => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
‘hostname’ => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
‘hostport’ => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
‘database’ => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
‘dsn’ => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
‘params’ => isset($_config['params'][$r])?$_config['params'][$r]:$_config['params'][0],
);
return $this->connect($db_config,$r);
}
[/php]
永远 取得第一个数据库,是主数据库,
有点迷糊了, 有空在详细分析(相当不详细)