mysql 连接闪断自动重连的方法

                       

使用php作为后台运行程序(例如短信群发),在cli模式下执行php,php需要连接mysql循环执行数据库处理。
当mysql连接闪断时,之后循环的执行将会失败。

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

1.创建测试数据表

CREATE TABLE `user``id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULLPRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  
  
  • 1
  • 2
  • 3
  • 4
  • 5


2.插入测试数据

insert into user(name) values('fdipzone'),('xfdipzone'),('terry');mysql> select * from user;+----+-----------+| id | name      |+----+-----------+|  1 | fdipzone  ||  2 | xfdipzone ||  3 | terry     |+----+-----------+
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10


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;    }}?>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

test.php

<?phprequire '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);}?>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31


4.执行步骤

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

mysql.server stopShutting down MySQL.. SUCCESS! mysql.server startStarting MySQL SUCCESS! 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

Array(    [0] => Array        (            [id] => 3            [name] => terry        ))sleep 10SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayArray()sleep 10SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayArray()sleep 10...
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23


5.增加重连机制

if(isset(self::$_instance) && !empty(self::$_instance)){    return self::$_instance;}
  
  
  • 1
  • 2
  • 3

闪断后,因为 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;        }    }}?>
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63


6.再次进行闪断执行

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

Array(    [0] => Array        (            [id] => 2            [name] => xfdipzone        ))sleep 10SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayArray()sleep 10Array(    [0] => Array        (            [id] => 1            [name] => fdipzone        ))sleep 10...
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28



源码下载地址:点击查看

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值