实际工作中遇到上一次数据库访问和下一次数据库访问超过wait_timeout的情况, 此时就会报Mysql has gone away的错误.
利用mysql_ping可以解决:
1 现在数据库抽象层加入重连功能:
/**
* 重新连接数据库
*/
private function reconnect() {
$link = $this->_master_arr;
$link['new_link'] = true;
$this->_mas_link = $this->addConnect ( $link );
$this->_use_mas = true;
$this->_link = $this->_mas_link;
}
/**
* 检查数据库连接是否可用,如果不可用尝试重新连接
*/
private function checkConnect() {
if (! mysql_ping ( $this->_mas_link )) {
$this->reconnect ();
}
}
2 然后在查询语句前加入检测是否需要重连
/**
* 执行sql
*
* @param string $sql
* @param bool use_mas 是否使用主链接
* @return 记录集
*/
public function query($sql,$forece_mas_link = false) {
$this->checkConnect();
($this->_sla_link || $this->_memcache ) && $this->_sql_table_arr = $this->getTableFromSql($sql);
if(!$forece_mas_link ) { //没有指定直接查询
$forece_mas_link = !($this->_sla_link || $this->_memcache);
if(!$forece_mas_link) { //至少有从数据库,或memcache中的一个
$forece_mas_link = $this->getForceMasLink($sql);
if(!$forece_mas_link) { //是select具select 的表没有更新
if($this->_memcache) {
$this->initMemcacheParam();
$this->_md5_sql = md5($sql);
if(false !== ($this->_data_lists = $this->_memcache->get($this->_md5_sql))) {
$this->_fetch_from_memcache = true;
$this->_max_len = count($this->_data_lists);
return;
}
}
}
}
}
$forece_mas_link && $this->_memcache && $this->_memcache->delTable($this->_sql_table_arr[0]) && $this->setForceMasArr($this->_sql_table_arr);
$this->_res = mysql_query($sql,$this->_link);
$this->_fetch_from_memcache = false;
if(((defined('DEBUG') && DEBUG)||(defined('IS_XMLRPC') && IS_XMLRPC)) && !$this->_res) {
//debug($sql);
$this->dbError('sql is:'.$sql);
die();
}
$this->_query_count++;
}