Mysql5数据库连接超时问题

来源:互联网 发布:淘宝职业打假人黑名单 编辑:程序博客网 时间:2024/04/28 15:03

问题描述:系统本来运行正常,但过一段时间,或待机一晚上后,第二天早上第一次登录总是失败。查看日志或Tomcat控制台输出,发现如下错误信息:

Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was41968 seconds ago.The last packet sent successfully to the server was 41968 seconds ago, which  is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

解决方法来自http://www.svn8.com/mysql/200906036013.html

http://i5tt.javaeye.com/blog/380324

经过一番调研,发现很多人都碰到过类似问题,但网上令人满意的回答并不多。mysql网站上的提问也很多,但并没有正确答案;百度知道上倒是有一个近似正确的回答。现将本人的解决办法总结一下:

  上述问题是由mysql5数据库的配置引起的。mysql5将其连接的等待时间(wait_timeout)缺省为8小时。在其客户程序中可以这样来查看其值:

  mysql

  mysql show global variables like 'wait_timeout';

  +---------------+---------+

  | Variable_name | Value |

  +---------------+---------+

  | wait_timeout | 28800 |

  +---------------+---------+

  1 row in set (0.00 sec)

  28800 seconds,也就是8小时。

  如果在wait_timeout秒期间内,数据库连接(java.sql.Connection)一直处于等待状态,mysql5就将该连接关闭。这时,你的JavaEE应用的连接池仍然合法地持有该连接的引用。当用该连接来进行数据库操作时,就碰到上述错误。这解释了为什么程序第二天不能登录的问题。

  你可能会想到在tomcat的数据源配置中有没有办法解决?的确,在jdbc连接url的配置中,你可以附上“autoReconnect=true”,但这仅对mysql5以前的版本起作用。增加“validation query”似乎也无济于事。

  本人觉得最简单的办法,就是对症下药:既然问题是由mysql5的全局变量wait_timeout的缺省值太小引起的,我们将其改大就好了。

  查看mysql5的手册,发现对wait_timeout的最大值分别是24/365(windows/linux)。以windows 例,假设我们要将其设为21天,我们只要修改mysql5的配置文件“my.ini(mysql5 installation dir)中的[mysqld]后面增加一行:wait_timeout=1814400

  需要重新启动mysql5

  linux系统配置文件:/etc/my.cnf

  测试显示问题解决了。

原创粉丝点击