• PHP连接MySql闪断自动重连的方法


    使用php作为后台运行程序(例如短信群发),在cli模式下执行php,php需要连接mysql循环执行数据库处理。

    当mysql连接闪断时,之后循环的执行将会失败。

    我们需要设计一个方法,当mysql闪断时,可以自动重新连接,使后面的程序可以正常执行下去。

    1.创建测试数据表

    CREATE TABLE `user` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(20) NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    2.插入测试数据

    insert into user(name) values('fdipzone'),('xfdipzone'),('terry');
    mysql> select * from user;
    +----+-----------+
    | id | name |
    +----+-----------+
    | 1 | fdipzone |
    | 2 | xfdipzone |
    | 3 | terry |
    +----+-----------+

    3.后台运行的php文件

    db.php

    <?php
    // 数据库操作类
    class DB{
    // 保存数据库连接
    private static $_instance = null;
    // 连接数据库
    public static function get_conn($config){if(isset(self::$_instance) && !empty(self::$_instance)){
    return self::$_instance;
    }
    $dbhost = $config['host'];
    $dbname = $config['dbname'];
    $dbuser = $config['user'];
    $dbpasswd = $config['password'];
    $pconnect = $config['pconnect'];
    $charset = $config['charset'];
    $dsn = "mysql:host=$dbhost;dbname=$dbname;";
    try {
    $h_param = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    );
    if ($charset != '') {
    $h_param[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $charset; //設置默認編碼
    }
    if ($pconnect) {
    $h_param[PDO::ATTR_PERSISTENT] = true;
    }
    $conn = new PDO($dsn, $dbuser, $dbpasswd, $h_param);
    } catch (PDOException $e) {
    throw new ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31);
    }
    self::$_instance = $conn;
    return $conn;
    }
    // 执行查询
    public static function query($dbconn, $sqlstr, $condparam){
    $sth = $dbconn->prepare($sqlstr);
    try{
    $sth->execute($condparam);
    } catch (PDOException $e) {
    echo $e->getMessage().PHP_EOL;
    }
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $result;
    }
    }
    ?>

    test.php

    <?php
    require 'db.php';
    // 数据库设定
    $config = array(
    'host' => 'localhost',
    'dbname' => 'user',
    'user' => 'root',
    'password' => '',
    'pconnect' => 0,
    'charset' => ''
    );
    // 循环执行
    while(true){
    // 创建数据连接
    $dbconn = DB::get_conn($config);
    // 执行查询
    $sqlstr = 'select * from user where id=?';
    $condparam = array(mt_rand(1,3));
    $data = DB::query($dbconn, $sqlstr, $condparam);
    print_r($data);
    // 延时10秒
    echo 'sleep 10'.PHP_EOL.PHP_EOL;
    sleep(10);
    }
    ?>

    4.执行步骤

    在php cli模式下执行test.php,然后马上执行mysql.server stop 与 mysql.server start 模拟闪断

    mysql.server stop
    Shutting down MySQL
    .. SUCCESS!
    mysql.server start
    Starting MySQL
    SUCCESS!

    可以看到,闪断后不能重新连接数据库,后面的程序不能执行下去。

    Array
    (
    [0] => Array
    (
    [id] => 3
    [name] => terry
    )
    )
    sleep 10
    SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
    Array
    (
    )
    sleep 10
    SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
    Array
    (
    )
    sleep 10
    ...

    5.增加重连机制

    if(isset(self::$_instance) && !empty(self::$_instance)){
    return self::$_instance;
    }

    闪断后,因为 self::$_instance 的值存在,因此调用get_conn并不会重新连接,而是使用保存的连接进行处理。

    这样实际上是当连接存在时,不需要再次创建mysql连接,减少mysql连接数。

    所以需要在闪断后,清空self::$_instance的值,使下次重新获取连接,而不使用已经创建但失效的数据库连接。

    改进方法如下:

    增加reset_connect方法,当出现错误时调用。如果判断错误是MySQL server has gone away则清空已经存在的数据库连接,清空后下次则会重新连接mysql。

    修改后的php文件如下:

    db.php

    <?php
    // 数据库操作类
    class DB{
    // 保存数据库连接
    private static $_instance = null;
    // 连接数据库
    public static function get_conn($config){if(isset(self::$_instance) && !empty(self::$_instance)){
    return self::$_instance;
    }
    $dbhost = $config['host'];
    $dbname = $config['dbname'];
    $dbuser = $config['user'];
    $dbpasswd = $config['password'];
    $pconnect = $config['pconnect'];
    $charset = $config['charset'];
    $dsn = "mysql:host=$dbhost;dbname=$dbname;";
    try {
    $h_param = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    );
    if ($charset != '') {
    $h_param[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $charset; //設置默認編碼
    }
    if ($pconnect) {
    $h_param[PDO::ATTR_PERSISTENT] = true;
    }
    $conn = new PDO($dsn, $dbuser, $dbpasswd, $h_param);
    } catch (PDOException $e) {
    throw new ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31);
    }
    self::$_instance = $conn;
    return $conn;
    }
    // 执行查询
    public static function query($dbconn, $sqlstr, $condparam){
    $sth = $dbconn->prepare($sqlstr);
    try{
    $sth->execute($condparam);
    } catch (PDOException $e) {
    echo $e->getMessage().PHP_EOL;
    self::reset_connect($e->getMessage()); // 出错时调用重置连接
    }
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $result;
    }
    // 重置连接
    public static function reset_connect($err_msg){
    if(strpos($err_msg, 'MySQL server has gone away')!==false){
    self::$_instance = null;
    }
    }
    }
    ?>

    6.再次进行闪断执行

    可以看到改进后的效果,闪断后,当前执行的会失败,但之后的可以重新创建新连接继续执行下去。

    Array
    (
    [0] => Array
    (
    [id] => 2
    [name] => xfdipzone
    )
    )
    sleep 10
    SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
    Array
    (
    )
    sleep 10
    Array
    (
    [0] => Array
    (
    [id] => 1
    [name] => fdipzone
    )
    )
    sleep 10
    ...

     文章同步发布: https://www.geek-share.com/detail/2683442734.html

  • 相关阅读:
    uvalive 3644 X-Plosives
    uva 11997 K Smallest Sums
    Codeforces Round #441 (Div. 2, by Moscow Team Olympiad) D. Sorting the Coins
    Codeforces Round #441 (Div. 2, by Moscow Team Olympiad) C. Classroom Watch
    Codeforces Round #441 (Div. 2, by Moscow Team Olympiad) B. Divisiblity of Differences
    Codeforces Round #441 (Div. 2, by Moscow Team Olympiad) A. Trip For Meal
    1004. 成绩排名 (20)
    1003. 我要通过!(20)
    1002. 写出这个数 (20)
    1001. 害死人不偿命的(3n+1)猜想 (15)
  • 原文地址:https://www.cnblogs.com/xxcn/p/9941377.html
Copyright © 2020-2023  润新知