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

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

当mysql链接闪断时,以后循环的执行将会失败。html

咱们须要设计一个方法,当mysql闪断时,能够自动从新链接,使后面的程序能够正常执行下去。mysql

1.建立测试数据表sql

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.phpfetch

<?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.phpui

<?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 模拟闪断server

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

相关文章
相关标签/搜索