mysql 自动断开时间_解决mysql默认的8小时自动断开连接

语言:javaEE

框架:spring mvc+spring+mybatis

数据库:mysql8

WEB服务器:tomcat8

背景:

在试运营阶段发现发生“连接超时”异常

抛出异常:

Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 353,479,051 milliseconds ago.  The last packet sent successfully to the server was 353,479,078 milliseconds ago. 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.

; SQL []; The last packet successfully received from the server was 353,479,051 milliseconds ago.  The last packet sent successfully to the server was 353,479,078 milliseconds ago. 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.; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 353,479,051 milliseconds ago.  The last packet sent successfully to the server was 353,479,078 milliseconds ago. 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.

原因分析:

MySQL服务器默认的“wait_timeout”是28800秒即8小时,意味着如果一个连接的空闲时间超过8个小时,MySQL将自动断开该连接,而连接池却认为该连接还是有效的(因为并未校验连接的有效性),当应用申请使用该连接时,就会导致上面的报错。

解决方案:

按异常信息所说,在MYSQL的JDBC连接串上加上autoReconnect=true

未能解决,据说这是针对mysql版本是5以前的。

2. 增加 MySQL 的 wait_timeout 属性的值

方法1 修改配置文件my.ini中的wait_timeout和interactive_timeout

方法2 使用mysql命令

set global wait_timeout=2880000;

set global interactive_timeout=2880000;

未能解决,原因未知

3. 减少连接池内连接的生存周期:减少连接池内连接的生存周期,使之小于上一项中所设置的wait_timeout 的值。

方法:修改 c3p0 的配置文件,在 Spring 的配置文件中设置:

未尝试。

4. 每隔一段时间往数据库发一条查询语句,这样使得数据库空闲时间不会太长,而使得其自动关闭。

方法:在SqlMapConfig.xml的dataSource进行如下配置:

开始的3行是关于数据库连接信息的,不需要说明了。

Pool.PingEnabled:是用于设置开启是否允许检测连接状态

Pool.PingQuery:是用于检测连接的查询语名,当然是越简单越好

Pool.PingConnectionOlderThan:对持续连接时间超过设定值(毫秒)的连接进行检测,我将其设置为0(不进行此项检测),否则,iBatis在超过这个时间后,执行每个sql以前检测连接,对于性能可能会有一定的影响。

Pool.PingConnectionsNotUsedFor:对空闲超过设定值(毫秒)的连接进行检测,我设置为1小时(mysql缺省的关闭时间是8小时)

成功!

点赞