MySQL:No operations allowed after connection closed错误原因及解决

Posted dxj1016

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL:No operations allowed after connection closed错误原因及解决相关的知识,希望对你有一定的参考价值。

错误

页面出现500,查看控制台错误出现No operations allowed after connection closed。

原因

出现No operations allowed after connection closed。错误
,说明mysql的链接已经关闭了。访问一个关闭了的链接当然会出现异常了。
之所以会出现这个异常,是因为MySQL5.0以后针对超长时间DB连接做了一个处理,那就是如果一个DB连接在无任何操作情况下过了8个小时后(Mysql 服务器默认的“wait_timeout”是8小时),Mysql会自动把这个连接关闭。这就是问题的所在,在连接池中的connections如果空闲超过8小时,mysql将其断开,而连接池自己并不知道该connection已经失效,如果这时有 Client请求connection,连接池将该失效的Connection提供给Client,将会造成上面的异常。
所以配置datasource时需要配置相应的连接池参数,定是去检查连接的有效性,定时清理无效的连接。

解决方法

在配置文件yml的数据源配置中添加如下连接池配置:

initialSize: 5
minIdle: 10
maxActive: 1000
#配置获取连接等待超时的时间
maxWait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
#配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
#指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.
testWhileIdle: true
#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
testOnBorrow: true
#指明是否在归还到池中前进行检验
testOnReturn: false

补充:spring boot默认会优先使用的连接池是tomcat连接池,前提是在tomcat连接池可用的情况下

参考资料1

以上是关于MySQL:No operations allowed after connection closed错误原因及解决的主要内容,如果未能解决你的问题,请参考以下文章

mysql链接出现: No operations allowed after statement closed.

java连接mysql出现异常No operations allowed after connection closed,怎么破?

com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.

com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.

com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after co