mysql出现ERROR : (2006, 'MySQL server has gone away') 的问题意思就是指client和MySQL server之间的链接断开了。数据库连接断开,重连机制
/**
* 获取连接.
*
* @param string $url
*
* @return Connection|null
*
* @throws \Exception
*/
protected function getConn($url)
{
$conn = null;
for ($times = 1; $times <= 3; ++$times) {
try {
$config = new Configuration();
$conn = DriverManager::getConnection(
array(
'url' => $url,
'driver' => 'pdo_mysql',
),
$config
);
break;
} catch (\Exception $e) {
$sleepTime = $times * 60 > 180 ? 180 : $times * 60;
sleep($sleepTime);
$logger->error(sprintf('第【%s】次获取数据库mysql连接异常, 异常信息为【%s】', $times, $url, $e->getMessage()));
}
}
return $conn;
}
public function checkDbGoneAway($conn)
{
$result = true;
try {
$conn->execute("select 1");
} catch (\Exception $e) {
$errMsg = $e->getMessage();
$errCode = $e->getCode();
if (2006 === $errCode && false !== strpos($errMsg, 'server has gone away')) {
$result = false;
}
}
return $result;
}
系统自带ping方法,不通不会出现异常
if (false === $conn->ping()) {
$conn->close();
$conn->connect();
}