ThinkPHP数据库读写分离机制源码解析
在使用原生SQL语句执行写入任务时,必须调用execute方法;而执行查询任务时,则应使用query方法。
MySQL的主从数据同步依赖于其自身的机制,因此主从同步产生的延迟问题亟待优化。过长的延迟时间不仅会干扰正常业务流程,还会降低用户的整体体验。
在ThinkPHP的核心类Thinkphp/library/Model.class.php中,query方法的实现逻辑会进一步调用Thinkphp/library/Think/Db/Driver/Mysql.class.php中的相关功能。
/**
* SQL查询
* @access public
* @param string $sql SQL
* @param mixed $parse 是否需要解析SQL
* @return mixed
*/
public function query($sql,$parse=false) {
if(!is_bool($parse) && !is_array($parse)) {
$parse = func_get_args();
array_shift($parse);
}
$sql = $this->parseSql($sql,$parse);
return $this->db->query($sql);
}
该过程具体涉及对Thinkphp/library/Think/Db/Driver/Mysql.class.php文件的调用。
/**
* 执行查询 返回数据集
* @access public
* @param string $str sql指令
* @return mixed
*/
public function query($str) {
if(0===stripos($str, 'call')){ // 存储过程查询支持
$this->close();
$this->connected = false;
}
$this->initConnect(false);
if ( !$this->_linkID ) return false;
$this->queryStr = $str;
//释放前次的查询结果
if ( $this->queryID ) { $this->free(); }
N('db_query',1);
// 记录开始执行时间
G('queryStartTime');
$this->queryID = mysql_query($str, $this->_linkID);
$this->debug();
if ( false === $this->queryID ) {
$this->error();
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}
在初始化数据库连接阶段,initConnect(false)被触发,此调用源自Thinkphp/library/Think/Db/Db.class.php。需注意其中布尔参数的含义:传入true表示直接连接主数据库,而传入false则表示启用读写分离策略,连接至从数据库。
/**
* 初始化数据库连接
* @access protected
* @param boolean $master 主服务器
* @return void
*/
protected function initConnect($master=true) {
if(1 == C('DB_DEPLOY_TYPE'))
// 采用分布式数据库
$this->_linkID = $this->multiConnect($master);
else
// 默认单数据库
if ( !$this->connected ) $this->_linkID = $this->connect();
}
/**
* 连接分布式服务器
* @access protected
* @param boolean $master 主服务器
* @return void
*/
protected function multiConnect($master=false) {
foreach ($this->config as $key=>$val){
$_config[$key] = explode(',',$val);
}
// 数据库读写是否分离
if(C('DB_RW_SEPARATE')){
// 主从式采用读写分离
if($master)
// 主服务器写入
$r = floor(mt_rand(0,C('DB_MASTER_NUM')-1));
else{
if(is_numeric(C('DB_SLAVE_NO'))) {// 指定服务器读
$r = C('DB_SLAVE_NO');
}else{
// 读操作连接从服务器
$r = floor(mt_rand(C('DB_MASTER_NUM'),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],
'charset' => isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],
);
return $this->connect($db_config,$r);
}
当query方法的参数设定为false时,系统执行读取操作;而对于删除、更新和增加等写操作,系统默认连接主库。这一点可以通过参考Thinkphp/library/Model.class.php中的delete、save和add操作得到验证,这些操作的参数通常设为true。
以上内容涵盖了本文的全部核心知识点,希望能对读者的学习有所助益,同时也恳请读者多多支持本站。