当前位置: 移动技术网 > IT编程>数据库>Mysql > PHP连接MySql闪断自动重连的方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

第二套住房贷款,特克斯县公共信息网,福彩3d三毛图库

使用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
...

以上所述是小编给大家介绍的php连接mysql闪断自动重连的方法,希望对大家有所帮助

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

相关文章:

验证码:
移动技术网