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

 

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

 

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

根据您提供的错误信息,看起来您的应用程序与 MySQL 服务器的连接在一段时间后超时了。错误消息建议您采取以下几种解决方法: 1. 检查连接的有效性:在使用连接之前,在应用程序中添加代码以定期检查连接的有效性。您可以使用一些简单的查询或操作来测试连接是否仍然有效,以防止超时发生。 2. 增加服务器配置的超时值:根据错误消息,您可以尝试增加 MySQL 服务器的配置值,以延长客户端超时时间。具体来说,您可以尝试增加 'wait_timeout' 参数的值。该参数控制了服务器在客户端无活动连接的情况下关闭连接之前等待的时间。您可以联系 MySQL 管理员或查阅相关文档来了解如何调整这些服务器配置参数。 3. 使用 Connector/J 连接属性:如果您正在使用 Java 编程语言,并且使用 Connector/J 驱动程序连接到 MySQL 服务器,您可以考虑在连接字符串中添加 'autoReconnect=true' 属性。这将告诉 Connector/J 在连接丢失后自动重新连接到服务器,从而避免超时问题。 例如,在 Java 中使用 Connector/J 进行连接时,您可以使用以下连接字符串: ```java String url = "jdbc:mysql://localhost:3306/database?autoReconnect=true"; ``` 请注意,自动重新连接可能会导致一些数据一致性问题,因此在使用时请谨慎考虑。 希望这些解决方法对您有所帮助!如果您有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值