Spring Boot communications link failure with MySQL and Hibernate
When you put a Spring Boot web application in production can happen that it will be inactive for several hours (e.g. for a whole night) without making any communication with database.
Using MySQL this can lead to a “communications link failure” error like this:
2015-07-08 09:16:32.666 WARN 20582 --- [http-nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08S01 2015-07-08 09:16:32.668 ERROR 20582 --- [http-nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Communications link failure The last packet successfully received from the server was 29.792.613 milliseconds ago. The last packet sent successfully to the server was 6 milliseconds ago.
MySQL has a wait timeout limit set for default to 8 hours (28800 seconds). If the database connection is inactive for more than 8 hours it is automatically closed and the error above will happen.
How to avoid this
In Spring Boot, we can solve this problem adding these configurations in the
spring.datasource.testWhileIdle = true spring.datasource.timeBetweenEvictionRunsMillis = 60000 spring.datasource.validationQuery = SELECT 1
hour (3600000 millis) minute (60000 millis) will be performed a connection test executing the query “SELECT 1”. In this way we can keep alive the database connection, periodically performing a validation query, and avoid to reach the MySQL’s wait_timeout.
MySQL wait_timeout and interactive_timeout