Home  >  Article  >  Backend Development  >  doctrine implements automatic reconnection to mysql database mechanism

doctrine implements automatic reconnection to mysql database mechanism

零到壹度
零到壹度Original
2018-04-03 16:43:271829browse

This article mainly introduces doctrine to realize the automatic reconnection of mysql database mechanism. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

I don’t know if you have encountered it. Sometimes mysql will automatically disconnect if it is not used for eight hours, which will cause our request to fail. , project access error, database disconnection, if this time expires, what should we do? We are using doctrine-dbal, so let’s write an automatic reconnection mechanism! Not much to say bb, just go straight to the code. <br>
doctrine implements automatic reconnection to mysql database mechanism

<?php
namespace WsdServer\Lib\PDO;

use Doctrine\Common\EventManager;

use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Cache\QueryCacheProfile;

use Doctrine\DBAL\Connection AS Connection;


/**
 * A wrapper around a Doctrine\DBAL\Connection that adds features like
 * reconnect
 *
 */
 class WsdConnection extends Connection
 {
    const RECONNECT_MAX_TIMES = 3;  // 最多重试次数

    private $reconnectRetryTimes;    
    
    public function __construct(array $params, Driver $driver, Configuration $config = null,
                                EventManager $eventManager = null)
    {
        parent::__construct($params, $driver, $config, $eventManager);
    }    
    
    /**
     * executeQuery - 支持自动重连机制的封装
     *
     * Executes an, optionally parametrized, SQL query.
     *
     * If the query is parametrized, a prepared statement is used.
     * If an SQLLogger is configured, the execution is logged.
     *
     * @param string $query The SQL query to execute.
     * @param array $params The parameters to bind to the query, if any.
     * @param array $types The types the previous parameters are in.
     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp The query cache profile, optional.
     *
     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
     *
     * @throws DBALException
     * @throws \Exception
     */
    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
    {
        try {            
             $result = parent::executeQuery($query, $params, $types, $qcp);            
             $this->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;
        }
    }

}

In this way, the current two methods are used to cover its original one, so that the connection mechanism is simple and good.
Tested one Wave, we found that if we kill mysql, it will automatically reconnect when it restarts. The reason is that it has a bottom layer, $this->connect(). So we don’t have to be afraid

The above is the detailed content of doctrine implements automatic reconnection to mysql database mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn