springboot druid连接池配置信息错误一直重试连接

配置数据库密码错误后,程序一直尝试连接,导致数据库用户被锁住

解决方法:

从源码中我们可以看到,线程中使用了无参for循环再一直尝试进行数据源连接,代码中【errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0】当满足该判断条件时就会进行重试连接,接下来我们看一下源码中这两个属性值设置的是什么呢?(源码过长,只展示我们需要的代码,其他属性信息可自行扒源码~)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static final long serialVersionUID = 1L;
public final static int DEFAULT_INITIAL_SIZE = 0;
public final static int DEFAULT_MAX_ACTIVE_SIZE = 8;
public final static int DEFAULT_MAX_IDLE = 8;
public final static int DEFAULT_MIN_IDLE = 0;
public final static int DEFAULT_MAX_WAIT = -1;
public final static String DEFAULT_VALIDATION_QUERY = null; //
public final static boolean DEFAULT_TEST_ON_BORROW = false;
public final static boolean DEFAULT_TEST_ON_RETURN = false;
public final static boolean DEFAULT_WHILE_IDLE = true;
public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = 60 * 1000L;
public static final long DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS = 500;
public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
/*****************************华丽的分割线中间省略代码若干行*********************************/
protected volatile long timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
protected int connectionErrorRetryAttempts = 1;
protected boolean breakAfterAcquireFailure = false;

从中这段代码中我们可以看到connectionErrorRetryAttempts值为1,timeBetweenConnectErrorMillis值为60000,而breakAfterAcquireFailure值为false,因此当我们数据源连接失败后,就会不断的进行重试连接,因此我对于对于该如何解决这样的问题我们就有了答案:

1.若不想让重试,我们可以设置breakAfterAcquireFailure(true);connectionErrorRetryAttempts(0);

2.若想要设置多久重试,我们只需要设置timeBetweenConnectErrorMillis(time);

action:经过亲测,直接在配置文件中配置属性并不能读取到(Druid设计时就这样,大神的思维暂时还不能参悟~),我们可直接将值写入程序当中,如下:

1
2
3
4
5
6
7
8
9
DruidDataSourceBuilder druidDataSourceBuilder = DruidDataSourceBuilder.create();
DruidDataSource druidDataSource = druidDataSourceBuilder.build();
List<Filter> listFileters = new ArrayList<>();
listFileters.add(getSlf4jLogFilter());
listFileters.add(getStatFilter());
// 设置失败重试次数为3次
druidDataSource.setBreakAfterAcquireFailure(true);
druidDataSource.setConnectionErrorRetryAttempts(3);
druidDataSource.setProxyFilters(listFileters);