当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP doctrine 数据库mysql自动重连机制示例讲解

PHP doctrine 数据库mysql自动重连机制示例讲解

2018年04月10日  | 移动技术网IT编程  | 我要评论

不知火舞之沙滩狂野,游戏王zexal69,重庆公务员

最可气的是mysql有的时候会八小时不使用的话自动断开连接,这样会导致我们的请求失败,项目访问报错,数据库断开

查看数据库等待时间是多少

这个时间要是失效了,那我们该怎么办呢?我们使用的是doctrine-dbal,所以那我们就写一套自动重连的机制吧!话不多bb,直接上代码。

reconnectRetryTimes = 0;
            return $result;
        } catch (DBALException $dex){
            if ( $dex->getErrorCode() == 2006 ) {
                if ($this->reconnectRetryTimes <= WsdConnection::RECONNECT_MAX_TIMES) {
                    $this->reconnectRetryTimes++;
                    secho("ORM-executeQuery", "MySQL Reconnect...("
                        . $this->reconnectRetryTimes . "/" . WsdConnection::RECONNECT_MAX_TIMES . ")");
                    $this->close();
                    return $this->executeQuery($query, $params, $types, $qcp);
                }
            }
            throw $dex;
        } catch (\Exception $ex) {
            throw $ex;
        }
    }


    /**
     * executeUpdate - 支持自动重连机制的封装
     *
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
     *
     * This method supports PDO binding types as well as DBAL mapping types.
     *
     * @param string $query The SQL query.
     * @param array $params The query parameters.
     * @param array $types The parameter types.
     *
     * @return integer The number of affected rows.
     *
     * @throws DBALException
     * @throws \Exception
     */
    public function executeUpdate($query, array $params = array(), array $types = array())
    {
        try {
            $result = parent::executeUpdate($query, $params, $types);
            $this->reconnectRetryTimes = 0;
            return $result;
        } catch (DBALException $dex){
            if ( $dex->getErrorCode() == 2006 ) {
                $this->reconnectRetryTimes++;
                if ($this->reconnectRetryTimes <= WsdConnection::RECONNECT_MAX_TIMES) {
                    secho("ORM-executeQuery", "MySQL Reconnect...("
                        . $this->reconnectRetryTimes . "/" . WsdConnection::RECONNECT_MAX_TIMES . ")");
                    $this->close();
                    parent::executeUpdate($query, $params, $types);
                }
            }
            throw $dex;
        } catch (\Exception $ex) {
            throw $ex;
        }
    }

}

这样用现在的两个方法覆盖了它原来本身的,这样从连机制简简单单的好了,

测试了一波,发现我们 kill mysql,在重新起来的时候他会自动重新连接,原因是它本身的底层有一个,$this->connect()。所以我们不用怕了

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网