Connection Timeout in Spring Boot with JPA and Hibernate
When utilizing Spring Boot with JPA-Hibernate and MySQL, you may encounter the following error:
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'.
This issue arises due to prolonged inactivity in the connection,導致伺服器終止連線。
Unrecommended Solution
One common yet discouraged approach is to enable connection testing on borrow:
spring.datasource.testOnBorrow=true spring.datasource.validationQuery=SELECT 1
Recommended Solution
A more comprehensive solution involves:
Setting the spring.datasource.url to include the autoReconnect property:
spring.datasource.url = jdbc:mysql://localhost:3306/test?autoReconnect=true
Specifying maximum active connections:
spring.datasource.max-active=10
Specifying initial connections:
spring.datasource.initial-size=5
Setting maximum and minimum idle connections:
spring.datasource.max-idle=5 spring.datasource.min-idle=1
Enabling connection validation:
spring.datasource.test-while-idle=true spring.datasource.test-on-borrow=true
Specifying the validation query and idle connection timeout:
spring.datasource.validation-query=SELECT 1 spring.datasource.time-between-eviction-runs-millis=5000 spring.datasource.min-evictable-idle-time-millis=60000
Note for HikariCP
In Spring Boot 2.x, the connection pool has been switched to HikariCP. Refer to the HikariCP documentation for further configuration options.
The above is the detailed content of Here are a few title options, focusing on the question-answer format and encompassing the article\'s content: **Option 1 (Focus on the Error):** * **Spring Boot JPA/Hibernate: How to Fix \"Co. For more information, please follow other related articles on the PHP Chinese website!