mysql 超时问题的解决办法

 问题:

com.mysql.jdbc.CommunicationsException: The last packet successfully received from the server was58129 seconds ago.The last packet sent successfully to the server was 58129 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.

这是由于连接闲置时间超过8小时,mysql就会自动断开连接。

 

解决办法:

  1. 如果是mysql 4之前的版本,可以按照提示在JDBC URL中使用autoReconnect属性,jdbc:mysql://linkscholar.org:3306/db?&autoReconnect=true。但是5之后就不起作用了。
  2. 如果使用hibernate的话,可以添加配置:

 

 <property name="connection.autoReconnect">true</property>
 <property name="connection.autoReconnectForPools">true</property>
 <property name="connection.is-connection-validation-required">true</property>

 

   3.  如果使用c3p0连接池:

 

<property name="hibernate.c3p0.acquire_increment">1</property> 
<property name="hibernate.c3p0.idle_test_period">0</property> 
<property name="hibernate.c3p0.timeout">0</property>
<property name="hibernate.c3p0.validate">true</property>

  

 

4. 从数据库本身解决(默认是28800,也就是8个小时):

 一种方式是,在mysql的配置文件中加入以下内容:

[mysqld]

wait_timeout=3153600

interactive_timeout=3153600

保存后,重新启动mysql。

第二种方式是,在mysql控制台里进行修改:

set global wait_timeout=3153600;

set global interactive_timeout=3153600;

 

设置完成后,可以通过mysql控制台的

show global variables like '%wait_timeout%';

命令查看:



这里我设置为30天,注意要加上global,不然查询的是会话变量。 

 

5.  使用ibatis的话,可以在数据源中加入以下检测配置:

<property name="Pool.PingEnabled" value="true"/>
<property name="Pool.PingQuery" value="select 1"/>
<property name="Pool.PingConnectionsOlderThan" value="0"/>
<property name="Pool.PingConnectionsNotUsedFor" value="3600000"/> 

 详细说明见参考3.

 

 

引用和参考:

http://blog.csdn.net/zljjava/article/details/7996091

http://hi.baidu.com/thinkinginlamp/item/2ddb2237a741d120b2c0c5fb

http://www.blogjava.net/usherlight/archive/2008/05/13/200164.html