如果想调试“MySQL server has gone away”的问题,可以这样重现:
修改配置文件:
[html] view plaincopy
- sudo vi /etc/mysql/my.cnf
做如下修改:
[html] view plaincopy
- [mysqld]
- wait_timeout = 30
- interactive_timeout = 30
重启服务:
[html] view plaincopy
- sudo /etc/init.d/mysql restart
编写如下php脚本
[php] view plaincopy
- $link = mysql_connect('127.0.0.1', 'root', 'root');
- if (!$link) {
- die('Could not connect: ' . mysql_error());
- }
- echo 'Connected successfully';
- sleep(31);
- $result = mysql_query('show variables;');
- if (!$result) {
- die('Invalid query: ' . mysql_error());
- }
- while ($row = mysql_fetch_assoc($result)) {
- var_dump($row);
- }
- mysql_free_result($result);
- mysql_close($link);
- ?>
执行:
[plain] view plaincopy
- $ php mysql.php
- Connected successfully
- Invalid query: MySQL server has gone away
或者在命令行下等30秒也可以看到这个错误了:
[plain] view plaincopy
- mysql> select variables like '%timeout';
- ERROR 2006 (HY000): MySQL server has gone away
- No connection. Trying to reconnect...
- Connection id: 40
- Current database: *** NONE ***
然后你就可以想干啥干啥了,比如加个mysql_ping让他实现自动重连:
[php] view plaincopy
- function get_conn() {
- $conn = mysql_connect('127.0.0.1', 'root', 'root');
- if (!$conn) {
- die('Could not connect: ' . mysql_error() . '\n');
- }
- return $conn;
- }
- $conn = get_conn();
- sleep(31);
- if (!mysql_ping($conn)) {
- mysql_close($conn);
- $conn = get_conn();
- echo 'Reconnect\n';
- }
- $result = mysql_query('show variables;');
- if (!$result) {
- die('Invalid query: ' . mysql_error());
- }
- while ($row = mysql_fetch_assoc($result)) {
- var_dump($row);
- }
- mysql_free_result($result);
- mysql_close($conn);
- ?>
另外,php文档里说mysql_ping可以自动重连,但经实验实际上还是需要用户自行处理重连的问题(也可能我的参数设置不对)。
如果使用的是C/C++,可以在连接建立后使用如下方法让mysql_ping具有自动重连功能:
[cpp] view plaincopy
- char mysql_reconnect = 1;
- mysql_options(mysql->conn, MYSQL_OPT_RECONNECT, (char *)&mysql_reconnect);