MySQL异常【数据库断开连接】:Communications link failure

一,异常信息以及解决办法

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通讯失败了,即连接失败。

     为此:程序打开数据库连接户,等到数据库操作时,发现连接被MySQL关闭掉了。而在MySQL这一层,MySQL5配置上默认将连接的等待时间(wait_timeout) 缺省为8小时。若连接超过8小时,会导致MySQL认为这个连接超时无效,然后进行关闭

解决办法:

1. 在jdbc连接URL的配置中,你可以加上autoRecordnect=true

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项是设置是否让后台线程定时检查连接池中连接的可用性。

二:根本解决办法:代码优化

猜你喜欢

转载自blog.csdn.net/Ecloss/article/details/84100303