com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception iscom.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 6,388 milliseconds ago. The last packet sent successfully to the server was 1,504 milliseconds ago. at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240)
异常分析:程序与MySQL通信失败了,即链接失败了。java
此为程序打开数据库链接后,等到作数据库操做时,发现链接被MySQL关闭掉了。而在MySQL这一层,MySQL5配置上默认将链接的等待时间(wait_timeout)缺省为8小时。链接超过8小时,会致使mysql认为这个链接超时无效,而后进行关闭。mysql
mysql﹥ mysql﹥ show global variables like 'wait_timeout'; +---------------+---------+ | Variable_name | Value | +---------------+---------+ | wait_timeout | 28800 | +---------------+---------+ 1 row in set (0.00 sec) 28800 seconds,也就是8小时。
解决办法(尝试方案顺序可为:(1)(3)(2)):
(1)在jdbc链接url的配置中,你能够附上“autoReconnect=true”,但这仅对mysql5之前的版本起做用。
(2)既然问题是由mysql5的全局变量wait_timeout的缺省值过小引发的,咱们将其改大就行了。
查看mysql5的手册,发现对wait_timeout的最大值分别是24天/365天(windows/linux)。以windows为 例,假设咱们要将其设为21天,咱们只要修改mysql5的配置文件“my.ini”(mysql5 installation dir),增长一行:wait_timeout=1814400 ,须要从新启动mysql5。
linux系统配置文件:/etc/my.cnf
(3)咱们能够将数据库链接池的 validateQuery、testOnBorrow(testOnReturn)打开,这样在 每次从链接池中取出且准备使用以前(或者使用完且在放入链接池以前)先测试下当前使用是否好用,若是很差用,系统就会自动destory掉。
或者testWhileIdle项是设置是否让后台线程定时检查链接池中链接的可用性。linux
相似问题:java.net.SocketException四大异常解决方案spring