加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

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

发布时间:2020-12-12 01:26:21 所属栏目:MySql教程 来源:网络整理
导读:《Mysql应用PHP连接MySql闪断自动重连的方法》要点: 本文介绍了Mysql应用PHP连接MySql闪断自动重连的方法,希望对您有用。如果有疑问,可以联系我们。 使用php作为后台运行程序(例如短信群发),在cli模式下执行php,php需要连接mysql循环执行数据库处理. MYSQ

《Mysql应用PHP连接MySql闪断自动重连的方法》要点:
本文介绍了Mysql应用PHP连接MySql闪断自动重连的方法,希望对您有用。如果有疑问,可以联系我们。

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

当mysql连接闪断时,之后循环的执行将会失败.MYSQL应用

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

1.创建测试数据表MYSQL应用

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.插入测试数据MYSQL应用

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

3.后台运行的php文件MYSQL应用

db.phpMYSQL应用

<?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; //O置默Ja
}
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.phpMYSQL应用

<?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,$condparam);
print_r($data);
// 延时10秒
echo 'sleep 10'.PHP_EOL.PHP_EOL;
sleep(10);
}
?>

4.执行步骤MYSQL应用

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

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

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

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.增加重连机制MYSQL应用

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

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

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

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

改进方法如下:MYSQL应用

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

修改后的php文件如下:MYSQL应用

db.phpMYSQL应用

<?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,$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.再次进行闪断执行MYSQL应用

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

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闪断自动重连的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的.在此也非常感谢大家对编程之家网站的支持!MYSQL应用

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读