MySQL连接闲置8小时自动断开连接解决方案

这篇博客探讨了MySQL因wait_timeout设置导致的连接超时问题,当连接闲置8小时后会被自动断开。解决方案包括在连接URL中添加'autoReconnect=true'参数,调整Hibernate配置以启用自动重连,或者修改MySQL配置文件增大wait_timeout值。此外,还提到了检查和测试连接有效性的必要性。

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

日志遇到问题

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 232,596,703 milliseconds ago. The last packet sent successfully to the server was 232,596,704 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小时 (8小时内没有进行数据库操作), mysql就会自动断开连接。

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

解决方案

一、如果不用hibernate的话, 则在 connection url中加参数: autoReconnect=true
二、用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文件中追加2条配置,并重启MySQL:

[mysqld]
wait_timeout=31536000
interactive_timeout=31536000

可执行SQL语句,验证是否修改成功:

show global variables like '%time%' ;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值