Chinaunix首页 | 论坛 | 博客
  • 博客访问: 312018
  • 博文数量: 103
  • 博客积分: 1590
  • 博客等级: 上尉
  • 技术积分: 1075
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-02 10:17
文章分类

全部博文(103)

文章存档

2013年(32)

2012年(7)

2010年(64)

我的朋友

分类: Mysql/postgreSQL

2013-04-16 23:17:08

来源: http://blog.csdn.net/ffb/article/details/8792009

如果想调试“MySQL server has gone away”的问题,可以这样重现:

修改配置文件:

  1. sudo vi /etc/mysql/my.cnf  

做如下修改:
  1. [mysqld]  
  2. wait_timeout = 30  
  3. interactive_timeout = 30  

重启服务:
  1. sudo /etc/init.d/mysql restart  

编写如下php脚本
  1. $link = mysql_connect('127.0.0.1''root''root');  
  2. if (!$link) {  
  3.     die('Could not connect: ' . mysql_error());  
  4. }  
  5. echo 'Connected successfully';  
  6.   
  7. sleep(31);  
  8. $result = mysql_query('show variables;');  
  9. if (!$result) {  
  10.     die('Invalid query: ' . mysql_error());  
  11. }  
  12. while ($row = mysql_fetch_assoc($result)) {  
  13.     var_dump($row);  
  14. }  
  15. mysql_free_result($result);  
  16.   
  17. mysql_close($link);  
  18. ?>  

执行:
[plain] view plaincopy
  1. $ php mysql.php   
  2. Connected successfully  
  3. Invalid query: MySQL server has gone away  

或者在命令行下等30秒也可以看到这个错误了:
[plain] view plaincopy
  1. mysql> select variables like '%timeout';  
  2. ERROR 2006 (HY000): MySQL server has gone away  
  3. No connection. Trying to reconnect...  
  4. Connection id:    40  
  5. Current database: *** NONE ***  

然后你就可以想干啥干啥了,比如加个mysql_ping让他实现自动重连:

  1. function get_conn() {  
  2.     $conn = mysql_connect('127.0.0.1''root''root');  
  3.     if (!$conn) {  
  4.         die('Could not connect: ' . mysql_error() . '\n');  
  5.     }  
  6.     return $conn;  
  7. }  
  8.   
  9. $conn = get_conn();  
  10.   
  11. sleep(31);  
  12. if (!mysql_ping($conn)) {  
  13.     mysql_close($conn);  
  14.     $conn = get_conn();  
  15.     echo 'Reconnect\n';  
  16. }  
  17.   
  18. $result = mysql_query('show variables;');  
  19. if (!$result) {  
  20.     die('Invalid query: ' . mysql_error());  
  21. }  
  22. while ($row = mysql_fetch_assoc($result)) {  
  23.     var_dump($row);  
  24. }  
  25. mysql_free_result($result);  
  26.   
  27. mysql_close($conn);  
  28. ?>  


另外,php文档里说mysql_ping可以自动重连,但经实验实际上还是需要用户自行处理重连的问题(也可能我的参数设置不对)。

如果使用的是C/C++,可以在连接建立后使用如下方法让mysql_ping具有自动重连功能:

  1. char mysql_reconnect = 1;   
  2. mysql_options(mysql->conn, MYSQL_OPT_RECONNECT, (char *)&mysql_reconnect);  




阅读(1305) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~