在spring-boot jpa hibernate中,连接到数据库在大于4小时小于24小时后断开。
在spring-boot jpa hibernate中,连接到数据库在大于4小时小于24小时后断开。
我有一个使用spring-boot、jpa-hibernate和mysql的应用程序。我遇到了以下错误日志:\n
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.
\n这是我的application.properties文件:\n
# 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
\n要解决此问题,我可以使用以下配置:\nspring.datasource.testOnBorrow=true\nspring.datasource.validationQuery=SELECT 1\n
\n但我检查了一下,这不是推荐的做法。所以有人能给我建议应该怎么解决这个错误吗?
问题的原因是连接到数据库的连接在4到24小时后会断开。出现这个问题的原因可能是连接超时或连接池配置不正确。解决方法是通过在JDBC URL中指定autoReconnect
属性来解决连接超时的问题,但这不是推荐的方法。另一种解决方法是在应用程序的生命周期中启用连接的验证。可以通过指定一些属性来实现连接池的配置,包括最大连接数、初始连接数、最小和最大空闲连接数、连接验证查询等。此外,可以调整连接验证和空闲连接清理的时间间隔。根据使用的连接池不同,还可以参考相关文档进行配置。
在Spring Boot 2.x中,默认的连接池由Tomcat JDBC切换到了HikariCP。如果使用Tomcat JDBC作为连接池,可以参考相关文档进行配置。另外,从Spring Boot 1.4.1开始,一些属性可能会被忽略,需要使用spring.datasource.tomcat
来设置Tomcat特定的属性。
需要注意的是,validation-query
的使用实际上是不推荐的,因为JDBC4有更好的/不同的连接验证方式。HikariCP会在可用时自动调用JDBC验证方法。
最后,关于autoReconnect
属性是否必要以及需要设置哪些最小属性来解决这个问题,可以根据具体的环境和需求进行调整和测试。