mysql timeout setting using the Connector / J connection property ‘autoReconnect

本文介绍了当应用程序遇到MySQL连接超时错误时的几种解决方法,包括调整JDBC连接属性、配置Hibernate及c3p0连接池参数以及修改MySQL服务器配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

最近发现应用隔段时间就不可用了,发现有如下的错误日志:

 

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 45,012,127 milliseconds ago.  The last packet sent successfully to the server was 45,012,127 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的超时时间设置导致的:如果连接空闲超过8小时(即没有任何数据库操作),mysql会自动的断开与应用的链接,但可通过重启tomcat(或者其他web容器)的方式来解决。

 

以下是解决方案:

 

方案一

如果你的jdbc链接的url上没有autoReconnect=true参数的话,就添加类似下面的参数:

 

jdbc.url = jdbc:mysql ://ipaddress: 3306/database?autoReconnect=true&autoReconnectForPools=true

&failOverReadOnly=false

 

方案二

如果你使用了hibernate的话,还可以用下面的方式来配置:

 

<property name=”connection.autoReconnect”>true</property>

<property name=”connection.autoReconnectForPools”>true</property>

<property name=”connection.is-connection-validation-required”>true</property>

 

如果你使用的是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>

 

 方案三

最坏的方案:修改mysql的配置问加你my.cnf,wait_timeout 31536000就是一年,够长了:

 

[Mysqld]

 

wait_timeout = 31536000

 

interactive_timeout = 31536000

 

修改后,重启即可

 

或者参考这篇文章http://www.2cto.com/database/201312/261593.html动态修改超时时间。

 

值得注意的是,这种设置方法会对有的mysql上的所有数据库和所有客户端都有效,而往往不同的应用对超时时间的要求可能不尽相同,所以这种方法需要慎重使用。

 

Reference

http://www.databaseskill.com/2615216/

http://www.2cto.com/database/201312/261593.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值