java全栈

springboot使用druid做数据源时,mysql重启连接

2023-02-09  本文已影响0人  蓝山牧童

首先吐槽下druid的维护,issue都2.4K了,阿里也不做处理。许多要命的配置文档里也没有提及,而且这些配置有的互相有影响。

一、情景描述

springboot+mysql的一般项目,项目启动后,mysql服务器宕机,mysql重启后,springboot应用却还是无法获得数据库连接

com.mysql.cj.jdbc.exceptions.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.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1644)
    at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1710)
    at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2777)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

此时的druid配置

spring:
  datasource:
    druid:
      fail-fast: true #快速失败,这个参数设置true,否则连接失败会不断重试,接口请求超时

二、数据库重启,连接池自愈

修改配置如下:

spring:
  datasource:
    druid:
      break-after-acquire-failure: false #这是关键
      connection-error-retry-attempts: 10 #尝试次数
      fail-fast: true
      time-between-connect-error-millis: 10000

break-after-acquire-failure:
true表示失败后断开,后期数据库恢复也不自动连接;
false表示失败后不断开, 新的请求都会尝试重新创建连接。默认为false

上一篇 下一篇

猜你喜欢

热点阅读