在开发环境中禁用 hikari 池

Disable hikari pool in development environment

开发环境中,spring boot with hikari、jdbc连接不稳定,闲置一段时间再调用api,会失败(猜测是网络不稳定导致的,因为在生产环境中是可以的)

2022-03-08 12:13:35.571 [http-nio-9090-exec-6] WARN  com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Failed to validate connection com.mysql.cj.jdbc.ConnectionImpl@72415749 (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value.

### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30038ms.] with root cause
com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.NativeSession.checkClosed(NativeSession.java:1209)
    at com.mysql.cj.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:567)
    at com.mysql.cj.jdbc.ConnectionImpl.setNetworkTimeout(ConnectionImpl.java:2484)
    at com.zaxxer.hikari.pool.PoolBase.setNetworkTimeout(PoolBase.java:550)
    at com.zaxxer.hikari.pool.PoolBase.isConnectionAlive(PoolBase.java:165)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:179)
    at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:155)
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:128)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157)

不过下次就ok了

因为是开发环境,对性能没有要求,所以想禁用连接池,也就是每次使用connection只是新建一个连接。

那么如何配置 spring.datasource.hikari.XXX 以禁用连接池并在每次使用时创建新的 jdbc 连接?

您可以使用不同的 datasource 作为 SimpleDriverDataSource

as of Spring Boot 2.3.x, the following works out of the box with no need to exclude anything:

spring.datasource.type=org.springframework.jdbc.datasource.SimpleDriverDataSource

您也可以查看 MySQL recommended settings