在项目测试阶段,发现第二天来了之后,测试服务器就访问不了了。看日志文件发现如下错误
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost
原因是与数据库断开连接了。
我们使用的是mysql数据库,通过语句
show global variables like 'wait_timeout';
查询出
wait_timeout 28800
单位为秒,可以知道mysql连接最大空闲时长为8h,所以经过一晚上后,数据库连接断开了。
解决方案一(推荐):
在application.properties文件中做如下配置,即可。
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis= 18800
由于我的项目使用了多数据源,所以需要单独为没个数据源配置
spring.datasource.db1.test-on-borrow=false
spring.datasource.db1.test-while-idle=true
spring.datasource.db1.time-between-eviction-runs-millis= 18800
spring.datasource.db2.test-on-borrow=false
spring.datasource.db2.test-while-idle=true
spring.datasource.db2.time-between-eviction-runs-millis= 18800
test-on-borrow 指明是否从池中取出连接前进行检验,如果检验失败,则从池中取出连接并尝试取出另一个。
test-while-idle 指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除。
time-between-eviction-runs-millis 在空闲连接回收器线程运行期间休眠的时间值,姨毫秒为单位。如果设置为非整数,则不运行空闲连接回收器线程。
解决方案二(不推荐)
使用语句
SET global wait_timeout = 28800;
修改最大空闲时长。