ThinkPHP5.0.*版本 cli模式下 MySQL连接超时
发表于:2026-06-10 21:30:20浏览:0次
使用版本:TP5.0.*、 thinkphp-queue 1.1.6
一:mysql 超时断线问题
队列任务运行一段时间,出现:[10501]SQLSTATE[HY000]: General error: 2006 MySQL server has gone away 报错。
解决方法和分析:
配置文件 database.php 中配置断线重连:
配置后虽然日志中会出现另一个报错:PDO::prepare (): send of 60 bytes failed with errno=32 Broken pipe,但并不影响程序运行结果。因为断线重连后,程序都会抛出错误。
二:捕获断线重连的异常
/**
* 释放查询结果
* @access public
*/
public function free()
{
// $this->PDOStatement = null;
try {
$this->PDOStatement = null;
} catch (Exception $e) {
Log::write("has error when free PDOStatement maybe mysql gone away,skip it:" . $e->getMessage(), log::DEBUG);
}
}
/**
* 是否断线
* @access protected
* @param \PDOException|\Exception $e 异常对象
* @return bool
*/
protected function isBreak($e)
{
if (!$this->config['break_reconnect']) {
return false;
}
$info = [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Error writing data to the connection',
'Resource deadlock avoided',
'failed with errno',
'bytes failed with errno=32 Broken pipe',
];
$error = $e->getMessage();
foreach ($info as $msg) {
if (false !== stripos($error, $msg)) {
return true;
}
}
return false;
}
