首页  >  文章  >  Java  >  如何在使用 Hibernate 的 Spring Boot 中防止 424 小时后数据库连接丢失?

如何在使用 Hibernate 的 Spring Boot 中防止 424 小时后数据库连接丢失?

Patricia Arquette
Patricia Arquette原创
2024-10-24 18:38:06203浏览

How to Prevent Database Connection Loss After 424 Hours in Spring Boot with Hibernate?

使用 Hibernate 解决 Spring Boot 424 小时后数据库连接丢失的问题

使用 JPA-Hibernate 和 MySQL 的 Spring Boot 应用程序在连接到数据库时出现问题424 小时后丢失。错误日志显示:

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):

<code class="properties"># Connection validation and pool configuration
spring.datasource.max-active=10
spring.datasource.initial-size=5
spring.datasource.max-idle=5
spring.datasource.min-idle=1

# Periodic connection validation
spring.datasource.test-while-idle=true
spring.datasource.validation-query=SELECT 1

# Idle connection management
spring.datasource.time-between-eviction-runs-millis=5000
spring.datasource.min-evictable-idle-time-millis=60000</code>

这些设置使连接池能够:

  • 建立最大数量的活动连接 (spring.datasource.max-active)。
  • 定期验证连接 (spring.datasource.test-while) -idle)。
  • 如果在指定时间内未使用空闲连接,则将其删除 (spring.datasource.min-evictable-idle-time-millis)。

通过实现通过这些配置,连接池将定期测试连接的有效性并替换已过时的连接,确保即使在长时间不活动后也能保持稳定的数据库连接。

以上是如何在使用 Hibernate 的 Spring Boot 中防止 424 小时后数据库连接丢失?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn