Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

最近启动项目,连接自己本地数据库时,出现了如下异常

ERROR [com.alibaba.druid.pool.DruidDataSource] - create connection error, url: jdbc:mysql://127.0.0.1:3306/db_local?serverTimezone=UTC&useSSL=false&autoReconnect=true, errorCode 0, state 08001 java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.

这其实就是数据库没开启导致,开启就可以了

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

 

所以最好,我们修改一下这个时间

解决问题步骤

1.mysql5以前的版本可以直接在jdbc连接url的配置中附加上“autoReconnect=true”。

2.将mysql的全局变量wait_timeout的值修改为最大。查看mysql5的手册,发现windows和linux下wait_timeout的最大值分别是24天和365天。

  • 在文件my.ini的最后增加一行:wait_timeout=1814400。(该文件,windows下在mysql的安装目录下,linux下位置为/etc/my.ini)笔者的目录为:MySQL\Data\MySQL Server 8.0下

  • 重启mysql。

 

具体异常如下:

[2019-04-20 18:05:24.161] [Druid-ConnectionPool-Create-1967852205] ERROR [com.alibaba.druid.pool.DruidDataSource] - create connection error, url: jdbc:mysql://127.0.0.1:3306/db_local?serverTimezone=UTC&useSSL=false&autoReconnect=true, errorCode 0, state 08001
java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:108)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:87)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:61)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:71)
	at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:932)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:857)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:444)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
	at com.alibaba.druid.filter.FilterChainImpl.connection_connect(FilterChainImpl.java:148)
	at com.alibaba.druid.filter.stat.StatFilter.connection_connect(StatFilter.java:211)
	at com.alibaba.druid.filter.FilterChainImpl.connection_connect(FilterChainImpl.java:142)
	at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1410)
	at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1464)
	at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:1969)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

 

上一篇:Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException


下一篇:Caused by: org.xml.sax.SAXParseException: 文件提前结束。