您的位置:首页 > 编程语言 > Java开发

springboot中JDBC连接超时问题

2019-01-25 18:12 696 查看

最近项目中有一个问题,电子保卡信息要写入数据库,但写入失败,报错

息是这样的:

The last packet successfully received from the server was 57,704,088 
milliseconds ago. The last packet sent successfully to the server was 
57,704,089 milliseconds ago. is longer than the server configured 
value of ‘wait_timeout’. You should consider either expiring and/or 
testing connection validity before use in your application, increasing 
the server configured values for client timeouts, or using the 
Connector/J connection property ‘autoReconnect=true’ to avoid this 
problem.

大体意思是上次成功接收报文的时间超过了数据库超时时间的值,为了解决这个问题,应当增加数据库的超时时间或者是启用数据库自动重连机制。所以我们可以用两种方法: 
1、从DB层解决问题:增大数据库连接超时时间 
2、从应用层解决问题:设置自动重连机制,即在一定时间之内与数据库重连一次

1 增大数据库连接超时时间


数据库的超时时间是指一个连接可空闲的最大时间,如超时时间是30分钟,则如果一个连接空闲了30分钟,那么该连接将断开。

我这里是MySql数据库,首先使用下面命令查询数据库超时时间大小:

SHOW  GLOBAL  VARIABLES LIKE  'wait_timeout';

显示结果如下:

这个是MySql设置的默认值,这里单位是秒,28800秒就是8小时。

想要重新设置超时时间可以用以下命令:

SET GLOBAL wait_timeout=28800;


但是数据库的连接超时时间不能设置太长,时间过长,导致过多的connection Sleep,占用较多系统资源。所以理论上虽然可以将超时时间设置的更大,但强列不推荐用这种方法。看一下第二种办法。

2 启用自动重连机制

需要对application.properties的datasource进行配置。我使用是mybatis连接数据库。

配置及具体含义

[code]#初始化连接
spring.datasource.initial-size=10
#最大空闲连接
spring.datasource.max-idle=20
#最小空闲连接
spring.datasource.min-idle=5
#最大连接数量
spring.datasource.max-active=50
#是否在自动回收超时连接的时候打印连接的超时错误
spring.datasource.log-abandoned=true
#是否自动回收超时连接
spring.datasource.remove-abandoned=true
#超时时间(以秒数为单位)
spring.datasource.remove-abandoned-timeout=180
##<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
spring.datasource.max-wait=1000
spring.datasource.test-while-idle=true
#检测数据库的查询语句
spring.datasource.validation-query=select 1 from dual
spring.datasource.test-on-borrow=true
#每隔五分钟检测空闲超过10分钟的连接
spring.datasource.min-evictable-idle-time-millis=600000
spring.datasource.time-between-eviction-runs-millis=300000

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: