mysql_ping实现数据库重连

实际工作中遇到上一次数据库访问和下一次数据库访问超过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++;
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值