欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL server has gone away

程序员文章站 2022-07-05 19:54:39
数据库连接断开,重连机制 /** * 获取连接. * * @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

相关标签: PHP