增加断线重连机制和开关

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' => '',
// Query类
'query' => '\\think\\db\\Query',
// 是否需要断线重连
'break_reconnect' => false,
];
// PDO连接参数
@@ -391,6 +393,9 @@ abstract class Connection
// 返回结果集
return $this->getResult($pdo, $procedure);
} 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());
}
}
@@ -446,6 +451,9 @@ abstract class Connection
$this->numRows = $this->PDOStatement->rowCount();
return $this->numRows;
} 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());
}
}
@@ -747,8 +755,9 @@ abstract class Connection
}
/**
* 关闭数据库
* 关闭数据库(或者重新连接)
* @access public
* @return $this
*/
public function close()
{
@@ -756,6 +765,18 @@ abstract class Connection
$this->linkWrite = null;
$this->linkRead = null;
$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;
}
/**
* 是否断线
* @access protected
* @param \PDOException $e 异常对象
* @return bool
*/
protected function isBreak($e)
{
if (false !== stripos($e->getMessage(), 'server has gone away')) {
return true;
}
return false;
}
}