使用druid数据源发生communication link failer异常

项目使用springBoot作为框架,使用Druid数据源,使用mysql版本为5.6。

线上出现错误  

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

在网上了解到:出现链接中断的原因是:mysql会中断l在一段时间内一直保持的空闲的连接,而连接池并没有抛弃任何的空闲连接。所以当程序在达到请求数据库的代码时,如果连接池将已经中断的连接分配给线程,就会出现link failer错误。

使用mysql4版本的,可以在url中使用autoReconnet设置自动连接:url=jdbc:mysql://localhost:3306/test?autoReconnect=true。

但是到了mysql5,autoReconnect就失效了。

解决办法:

  办法一:修改mysql的内置变量。

      查询timeout变量:使用语句show variables like '%timeout%';   会出现与timeout相关的变量。

这里面,我们仅需要关注两个变量:wait_timeout、interactive_timeout。它们默认都是8小时。最大值是一年。一定要将这两个变量一起改,使用语句set gloal variables wait_timeout = 28800;

改变之后要记得重启mysql才可以。

  办法二:修改代码层面连接池配置。下面贴出可用的springboot配置

 1 sharding:
 2   jdbc:
 3     datasource:
 4       names: master
 5       master:
 6         type: com.alibaba.druid.pool.DruidDataSource
 7         driver-class-name: com.mysql.jdbc.Driver
 8         url: jdbc:mysql://localhost:3358/test
 9         username: root
10         password: 123456
11         #自动检测连接开关
12         testWhileIdle: true
13         #检测语句
14         validationQuery: select 1
15         #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
16         #因为我自己配置的是空闲连接1分钟断开,所以此处测试连接间隔为55s
17         timeBetweenEvictionRunsMillis: 55000
springboot 的druid配置

猜你喜欢

转载自www.cnblogs.com/aleda-territory/p/12601297.html