Home >Database >Mysql Tutorial >How to Resolve Spring Boot JPA/Hibernate Database Connection Interruptions?
Resolving Database Connection Interruptions in Spring Boot with jpa-hibernate
The error message indicates that the connection between your Spring Boot application and MySQL database has been terminated due to inactivity exceeding the server's configured wait timeout. To address this issue, there are several recommended approaches:
1. Enabling AutoReconnect:
An immediate solution is to enable auto-reconnection in the JDBC URL:
spring.datasource.url = jdbc:mysql://localhost:3306/test?autoReconnect=true
However, this method is not recommended as it can lead to unexpected behavior during active transactions.
2. Connection Validation:
A more effective approach is to enable connection validation throughout your application's lifetime. Configure the following properties:
Maximum active connections:
spring.datasource.max-active=10
Initial connections:
spring.datasource.initial-size=5
Idle connection limits:
spring.datasource.max-idle=5 spring.datasource.min-idle=1
Validation query and timing:
spring.datasource.test-while-idle=true spring.datasource.test-on-borrow=true spring.datasource.validation-query=SELECT 1 spring.datasource.time-between-eviction-runs-millis=5000 spring.datasource.min-evictable-idle-time-millis=60000
This configuration ensures that idle connections are validated regularly, and broken connections are removed from the pool.
3. HikariCP Connection Pool:
Spring Boot 2.x defaults to using HikariCP as the connection pool. HikariCP provides automatic connection validation, so the validation-query property can be omitted.
Note: While using a validation query is discouraged, HikariCP has its own method of connection validation, which is more efficient.
The above is the detailed content of How to Resolve Spring Boot JPA/Hibernate Database Connection Interruptions?. For more information, please follow other related articles on the PHP Chinese website!