在 spring-boot jpa hibernate 中 >4<24 后与 Db 的连接终止

Connection to Db dies after >4<24 in spring-boot jpa hibernate

我有一个应用程序使用 spring-boot,jpa-hiberanate mysql.I 我收到这个错误日志

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 56,006,037 milliseconds ago.  The last packet sent successfully to the server was 56,006,037 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

这是我的application.properties

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = test
spring.datasource.password = test
spring.datasource.driverClassName = com.mysql.jdbc.Driver

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy

为了解决这个问题我可以使用

spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1

但我检查过它不是 recommended。所以谁能建议我应该怎么做才能克服这个错误

最简单的方法是在 JDBC url 中指定 autoReconnect 属性,尽管这不是推荐的方法。

spring.datasource.url = jdbc:mysql://localhost:3306/test?autoReconnect=true

当您有活动连接并且在交易期间发生某些事情并且将要重新连接时,这可能会出现问题。在事务开始时验证连接并在开始时获取新连接时不会出现问题。

然而,在应用程序的生命周期内启用连接验证可能会更好。为此,您可以指定 several properties.

首先指定您允许池的最大连接数。 (有关确定最大池大小的阅读 this)。

spring.datasource.max-active=10

您可能还想指定初始连接数

spring.datasource.initial-size=5

接下来您要指定最小和最大空闲连接数。

spring.datasource.max-idle=5
spring.datasource.min-idle=1

要验证连接,您需要指定验证查询和验证时间。因为你想定期验证,而不是在从池中检索连接时验证(这是为了防止池中的连接断开)。

spring.datasource.test-while-idle=true
spring.datasource.test-on-borrow=true
spring.datasource.validation-query=SELECT 1

注意: 实际上不鼓励使用 validation-query,因为 JDBC4 有一个 better/different 进行连接验证的方式。 HikariCP 将在可用时自动调用 JDBC 验证方法。

既然您也在连接空闲时进行验证,您需要指定您想要运行此连接查询的频率以及连接何时被视为空闲。

spring.datasource.time-between-eviction-runs-millis=5000 (this is the default)
spring.datasource.min-evictable-idle-time-millis=60000 (this is also default)

这一切都应该触发对您的(空闲)连接的验证,并且当发生异常或空闲期已过时,您的连接将从池中删除。

假设您正在使用 Tomcat JDBC 作为连接池 this 很好地了解了配置内容和配置方式。

更新: Spring 启动 2.x 将默认连接池切换为 HikariCP 而不是 Tomcat JDBC。