为什么会被mysql中断连接呢,因为mysql有一个空闲waittimeout连接超时时长的参数,当一个连接超过这个时间没有做任何操作的情况下就会被自动断开,那么我们可以使用druid定时检测心跳,以实现连接不中断的效果,如下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Druid配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
//配置连接存活的重要参数
//空闲多久检测执行一次validation-query
spring.datasource.druid.time-between-eviction-runs-millis=60000
//空闲多久将被踢出连接池
spring.datasource.druid.min-evictable-idle-time-millis=300000
//心跳检测执行的sql
spring.datasource.druid.validation-query=SELECT 1
空闲时是否检测连接是否有效,这里开启,心跳检测才会开启
spring.datasource.druid.test-while-idle=true
//借用连接时是否检测连接是否有效。不建议开启,影响性能
spring.datasource.druid.test-on-borrow=false
//归还连接时是否检测连接是否有效。不建议开启,影响性能
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500