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