MySQL server has gone away
程序员文章站
2022-03-22 15:37:17
数据库连接断开,重连机制 /** * 获取连接. * * @param string $url * * @return Connection|null * * @throws \Exception */ protected function getConn($url) { $conn = null; for ($times = 1; $times <= 3; +...
数据库连接断开,重连机制
/**
* 获取连接.
*
* @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 query($sql, $param = [])
{
$times = 0;
retry:
try {
$this->clearParam();
$pre = $this->pdo->prepare($sql);
if (!$pre) {
return false;
}
$pre->execute($param);
return $pre->fetchAll(\PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
$error_code = $this->pdo->errorInfo()[1];
$error_msg = $this->pdo->errorInfo()[2];
if ($error_code === 2006) {
if ($times < 1) {
++$times;
$this->connect();
goto retry;
}
}
$this->logger->error(sprintf('数据库查询失败,错误信息:【ERROR %s】,SQL语句:【%s】', $error_code . '(' . $this->pdo->errorCode() . ') ' . $error_msg, $sql));
return false;
} catch (\Exception $e) {
$logger->error(sprintf('数据库操作异常,异常信息:【%s】', $e->getMessage()));
return false;
}
}
本文地址:https://blog.csdn.net/hudeyong926/article/details/111038261
上一篇: 炒菠菜的时候要不要焯水?菠菜怎么挑选?
推荐阅读
-
MySQL server has gone away 问题的解决方法
-
MySQL server has gone away 问题的解决方法
-
MySQL server has gone away错误提示解决方法
-
gearman中worker常驻后台,导致MySQL server has gone away的解决方法
-
MySQL server has gone away错误提示解决方法
-
gearman中worker常驻后台,导致MySQL server has gone away的解决方法
-
mysql导入大批量数据出现MySQL server has gone away的解决方法
-
mysql导入大批量数据出现MySQL server has gone away的解决方法
-
MySQL server has gone away
-
MySQL报错合集解决办法: server has gone away, @@GLOBAL.GTID_PURGED can only be set when @@GLOBAL.GTID_MODE = ON