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


问题:
通过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中增加配置
  
   
   
   
  
    
SELECT 1  
  
  
true  
  


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

你可能感兴趣的:(Spring连接mysql长时间空闲报错:The last packet successfully received from the server was xx millisecond ago...)