我有一个 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 文件中配置数据源以使应用程序重新连接到数据库,如回答 here和 here .但这不适用于与数据源的启动连接。
如何让我的 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/