增加断线重连机制和开关

This commit is contained in:
thinkphp
2017-01-30 20:06:02 +08:00
parent aa7a5e8c32
commit 88dab63314
2 changed files with 36 additions and 1 deletions

View File

@@ -108,6 +108,8 @@ abstract class Connection
'builder' => '', 'builder' => '',
// Query类 // Query类
'query' => '\\think\\db\\Query', 'query' => '\\think\\db\\Query',
// 是否需要断线重连
'break_reconnect' => false,
]; ];
// PDO连接参数 // PDO连接参数
@@ -391,6 +393,9 @@ abstract class Connection
// 返回结果集 // 返回结果集
return $this->getResult($pdo, $procedure); return $this->getResult($pdo, $procedure);
} catch (\PDOException $e) { } catch (\PDOException $e) {
if ($this->config['break_reconnect'] && $this->isBreak($e)) {
return $this->close()->query($sql, $bind, $master, $pdo);
}
throw new PDOException($e, $this->config, $this->getLastsql()); throw new PDOException($e, $this->config, $this->getLastsql());
} }
} }
@@ -446,6 +451,9 @@ abstract class Connection
$this->numRows = $this->PDOStatement->rowCount(); $this->numRows = $this->PDOStatement->rowCount();
return $this->numRows; return $this->numRows;
} catch (\PDOException $e) { } catch (\PDOException $e) {
if ($this->config['break_reconnect'] && $this->isBreak($e)) {
return $this->close()->execute($sql, $bind);
}
throw new PDOException($e, $this->config, $this->getLastsql()); throw new PDOException($e, $this->config, $this->getLastsql());
} }
} }
@@ -747,8 +755,9 @@ abstract class Connection
} }
/** /**
* 关闭数据库 * 关闭数据库(或者重新连接)
* @access public * @access public
* @return $this
*/ */
public function close() public function close()
{ {
@@ -756,6 +765,18 @@ abstract class Connection
$this->linkWrite = null; $this->linkWrite = null;
$this->linkRead = null; $this->linkRead = null;
$this->links = []; $this->links = [];
return $this;
}
/**
* 是否断线
* @access protected
* @param \PDOException $e 异常
* @return bool
*/
protected function isBreak($e)
{
return false;
} }
/** /**

View File

@@ -129,4 +129,18 @@ class Mysql extends Connection
{ {
return true; return true;
} }
/**
* 是否断线
* @access protected
* @param \PDOException $e 异常对象
* @return bool
*/
protected function isBreak($e)
{
if (false !== stripos($e->getMessage(), 'server has gone away')) {
return true;
}
return false;
}
} }