mysql报错:Caused by: com.mysql.cj.exceptions.CJCommunicationsException: The last packet successfully r
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: The last packet successfully received from the server was 35,813 milliseconds ago. The last packet sent successfully to the server was 35,813 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.
原因分析:
MySQL连接时,服务器默认的“wait_timeout”是8小时,也就是说一个connection空闲超过8个小时,Mysql将自动断开该connection。connections如果空闲超过8小时,Mysql将其断开,而DBCP连接池并不知道该connection已经失效,如果这时有Client请求connection,DBCP将该失效的Connection提供给Client,将会造成异常。
1,首先进入mysql,查看 wait_timeout、interactive_timeout这个值是否为默认的8小时(即 28800)
其中wait_timeout就是负责超时控制的变量,其时间为长度为28800s,就是8个小时,那么就是说MySQL的服务会在操作间隔8小时后断开,需要再次重连。也有用户在URL中使用jdbc.url=jdbc:mysql://localhost:3306/nd?autoReconnect=true来使得连接自动恢复,当然了,这是可以的,不过是MySQL4及其以下版本适用。MySQL5中已经无效了
解决方式一:修改msyql 配置 ,不推荐
解决方式二:保证应用在MySQL的’wait_timeout’时间内,至少访问一次数据库,配置文件增加心跳检测部分
sys.db.initialSize=10
sys.db.maxIdle=50
sys.db.minIdle=5
sys.db.maxActive=50
sys.db.logAbandoned=true
sys.db.removeAbandoned=true
sys.db.removeAbandonedTimeout=120
sys.db.maxWait=60000
sys.db.type=mysql
dialect=MYSQL
sys.db.class=com.mysql.jdbc.Driver
sys.db.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8
sys.db.username=root
sys.db.password=123456
# 28800 8小时
# 21600 6小时
show variables like '%timeout%';
SET GLOBAL wait_timeout=21600;
SET wait_timeout=21600;
SHOW GLOBAL VARIABLES LIKE 'wait_timeout';
SHOW VARIABLES LIKE 'wait_timeout';
SET GLOBAL interactive_timeout=58800;
SET interactive_timeout=58800;
SHOW GLOBAL VARIABLES LIKE 'interactive_timeout';
SHOW VARIABLES LIKE 'interactive_timeout';
连接池内连接的生存周期(idleConnectionTestPeriod)小于数据库中的wait_timeout的值
解决方式二:保证应用在MySQL的'wait_timeout'时间内,至少访问一次数据库,配置文件增加心跳检测部分
timeBetweenEvictionRunsMillis: 20800 # 配置间隔多久才进行一次检测 原值 :60000 改小与timeout时间.
idleConnectionTestPeriod: 20800 # 连接池内连接的生存周期(idleConnectionTestPeriod)小于数据库中的wait_timeout的值
minEvictableIdleTimeMillis: 18000000 # 1000 * 60 * 30 =18000000 (默认值) 连接在池中保持空闲而不被空闲连接回收器线程,(如果有)回收的最小时间值,单位毫秒
durid配置:
timeBetweenEvictionRunsMillis: 20800 # 配置间隔多久才进行一次检测 原值 :60000 改小与timeout时间.
idleConnectionTestPeriod: 20800 # 连接池内连接的生存周期(idleConnectionTestPeriod)小于数据库中的wait_timeout的值
minEvictableIdleTimeMillis: 18000000 # 1000 * 60 * 30 =18000000 (默认值) 连接在池中保持空闲而不被空闲连接回收器线程,(如果有)回收的最小时间值,单位毫秒
true false false select 1 1 28700 ${sys.db.maxActive} 18000000