Spring连接mysql长时间空闲报错:The last packet successfully received from the server was xx millisecond ago...

在Spring连接MySQL时遇到因等待超时导致的CommunicationsException异常。通过修改MySQL配置文件`my.ini`的`wait_timeout`值或者在Spring的`dataSource`配置中使用`validationQuery`和`testOnBorrow`属性来验证和重新建立连接,可以有效解决这个问题。

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

问题:
通过spring 连接 mysql 会出现报错
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 1,924,852 milliseconds ago. The last packet sent successfully to the server was 4 milliseconds ago.
以及
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
问题在于mysql 连接闲置一定时间后,mysql数据库就会自动断开连接,spring 的 jdcp 连接池中的connection是无效的,导致报错(使用数据库连接工具同样也会报错)
测试:
将mysql my.ini 配置文件中 wait_timeout设置为足够大,应可以解决上面的问题。测试将 wait_timeout=60 ,可以看到应用访问数据库经常会报错。
解决:
网上有不少的方案了,如果不用hibernate的话, 则在 connection url中加参数: autoReconnect=true,在spring 配置中测试无效。
经过测试可以在AndroidManifest.xml dataSource中增加配置
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
  <property name="url" value="jdbc:mysql://192.168.145.128:3306/mpps" /> 
  <property name="username" value="xxx" /> 
  <property name="password" value="xxx" />
  <property name="validationQuery">  
<value>SELECT 1</value>  
</property>  
<property name="testOnBorrow">  
<value>true</value>  
</property>  
</bean>


说明:
validationQuery SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前.如果指定,
则查询必须是一个SQL SELECT并且必须返回至少一行记录
testOnBorrow true 指明是否在从池中取出连接前进行检验,如果检验失败,
则从池中去除连接并尝试取出另一个.
这样虽然会有一点开销,但基本不影响,可以忽略
参考:
dbcp 配置参考了:http://blog.youkuaiyun.com/fairyhawk/article/details/7565391
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值