gpt4 book ai didi

Spring Boot JPA - 配置自动重新连接

转载 作者:IT老高 更新时间:2023-10-28 13:01:11 26 4
gpt4 key购买 nike

我有一个不错的小型 Spring Boot JPA Web 应用程序。它部署在 Amazon Beanstalk 上并使用 Amazon RDS 来保存数据。然而,它并不经常使用,因此在一段时间后会出现这种异常:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 79,870,633 milliseconds ago.
The last packet sent successfully to the server was 79,870,634 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.

我不确定如何配置此设置,也无法在 http://spring.io 上找到相关信息(虽然是一个非常好的网站)。有哪些想法或信息指针?

最佳答案

我假设 boot 正在为您配置 DataSource。在这种情况下,由于您使用的是 MySQL,您可以将以下内容添加到您的 application.properties 最高 1.3

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

正如 djxak 在评论中指出的那样,1.4+ 为 Spring Boot 支持的四个连接池定义了特定的命名空间:tomcathikaridbcp , dbcp2(dbcp 自 1.5 起已弃用)。您需要检查您正在使用的连接池并检查该功能是否受支持。上面的例子是针对 tomcat 的,所以你必须在 1.4+ 中编写如下:

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

注意autoReconnect的使用是not recommended :

The use of this feature is not recommended, because it has side effects related to session state and data consistency when applications don't handle SQLExceptions properly, and is only designed to be used when you are unable to configure your application to handle SQLExceptions resulting from dead and stale connections properly.

关于Spring Boot JPA - 配置自动重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22684807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com