MySQL server has gone away

2022-07-26,

数据库连接断开,重连机制

    /**
     * 获取连接.
     *
     * @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.doc》

下载本文的Word格式文档,以方便收藏与打印。