MySQL server has gone away

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();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值