mysql - Spring 重试连接直到数据源可用

标签 mysql spring spring-boot docker-compose hikaricp

我有一个 docker-compose 设置来启动我的 SpringBoot 应用程序和一个 MySQL 数据库。如果数据库先启动,那么我的应用程序就可以成功连接。但是如果我的应用程序先启动,还没有数据库存在,那么应用程序会抛出以下异常并退出:

app_1       | 2018-05-27 14:15:03.415  INFO 1 --- [           main]
com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
app_1       | 2018-05-27 14:15:06.770 ERROR 1 --- [           main]
com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization
app_1       | com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure

我可以编辑我的 docker-compose 文件以确保数据库在应用程序启动之前始终处于启动状态,但我希望应用程序能够自行处理这种情况,而不是在无法到达时立即退出数据库地址。

有一些方法可以在 application.properties 文件中配置数据源以使应用程序重新连接到数据库,如回答 herehere .但这不适用于与数据源的启动连接。

如何让我的 SpringBoot 应用程序在启动时以给定的时间间隔重试连接到数据库,直到它成功连接到数据库?

最佳答案

将 HikariCP 的 initializationFailTimeout 属性设置为 0(零)或负数。如记录here :

initializationFailTimeout

This property controls whether the pool will "fail fast" if the pool cannot be seeded with an initial connection successfully. Any positive number is taken to be the number of milliseconds to attempt to acquire an initial connection; the application thread will be blocked during this period. If a connection cannot be acquired before this timeout occurs, an exception will be thrown. This timeout is applied after the connectionTimeout period. If the value is zero (0), HikariCP will attempt to obtain and validate a connection. If a connection is obtained, but fails validation, an exception will be thrown and the pool not started. However, if a connection cannot be obtained, the pool will start, but later efforts to obtain a connection may fail. A value less than zero will bypass any initial connection attempt, and the pool will start immediately while trying to obtain connections in the background. Consequently, later efforts to obtain a connection may fail. Default: 1

关于mysql - Spring 重试连接直到数据源可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50553352/

相关文章:

php - Wordpress get_results from mysql where string 没有给出结果

mysql - MySQL 存储函数中的 FLOAT 类型可以被截断吗?

MySQL '@' : what does it do?

java - 如何使用 Cucumber runner 加载 Spring 应用程序上下文

java - 作为 byte[] 发送的字符串内容将其内容转义为查询字符串

model-view-controller - 更改 Spring-boot 静态 Web 资源位置?

spring-boot - Spring安全错误循环 View 路径[index] : would dispatch back to the current handler URL [/index] again.检查您的ViewResolver设置

php - 导出sql数据库时utf8列中的乱码数据

java - 使用 graphql-java-tools 和 graphql-spring-boot-starter 进行错误处理

java - 依赖 jar 中的 Spring Lazy Init = true