在mybatis多数据源配置下,为什么需要添加test-while-idle等参数来解决连接关闭问题?这个问题在单数据源环境下并不常见,但切换到多数据源配置后,可能会遇到”no operations allowed after connection closed”的错误。让我们探讨一下这个问题,并了解为什么需要这些配置。

关于MyBatis多数据源配置引发的连接关闭问题
在使用MyBatis进行数据库操作时,切换到多数据源配置后,可能会遇到”No operations allowed after connection closed”的错误。之前在单数据源环境下,这种问题并未出现过,也没有配置过类似test-while-idle=true的参数。那么,为什么在多数据源环境下需要这些配置呢?
在多数据源配置之前,单数据源的配置如下:
# 单数据源配置spring.datasource.url=jdbc:mysql://localhost:3306/db1spring.datasource.username=rootspring.datasource.password=password
切换到多数据源配置后,配置变成了:
# 多数据源配置spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1spring.datasource.primary.username=rootspring.datasource.primary.password=passwordspring.datasource.test1.url=jdbc:mysql://localhost:3306/db2spring.datasource.test1.username=rootspring.datasource.test1.password=password
然而,在多数据源环境下,出现了”No operations allowed after connection closed”的错误。网上搜索发现,需要添加以下MyBatis相关的配置:
spring.datasource.primary.test-while-idle=truespring.datasource.primary.time-between-eviction-runs-millis=18000
那么,添加这些配置是否能解决问题呢?为什么在单数据源环境下不需要这些配置?
是的,添加上述配置通常能解决这个问题,特别是这些关键参数:
spring.datasource.primary.test-while-idle=truespring.datasource.primary.time-between-eviction-runs-millis=18000
对于每个数据源,都需要类似配置:
uBrand Logo生成器
uBrand Logo生成器是一款强大的AI智能LOGO设计工具。
124 查看详情
# 主数据源spring.datasource.primary.test-while-idle=truespring.datasource.primary.validation-query=SELECT 1测试数据源
spring.datasource.test1.test-while-idle=truespring.datasource.test1.validation-query=SELECT 1
配置说明
test-while-idle=true:
关键配置,让连接池定期检查空闲连接是否有效。避免使用已关闭的连接。
validation-query:
用于测试连接是否有效的SQL。通常使用轻量级查询如”SELECT 1″。
time-between-eviction-runs-millis:
空闲连接检查的时间间隔。18000毫秒(18秒)是个合理值。
min-idle 和 max-idle:
控制连接池中保持的最小和最大空闲连接数。
为什么需要这些配置
多数据源环境下,某些数据源可能较少使用,导致连接长时间空闲。数据库服务器通常会关闭长时间空闲的连接(如MySQL默认8小时)。如果应用尝试使用这些已关闭的连接,就会出现”No operations allowed after connection closed”错误。
通过启用test-while-idle和设置validation-query,连接池会定期验证连接是否有效,及时关闭无效连接并创建新连接,从而避免使用已关闭的连接。
以上就是为什么在MyBatis多数据源配置下需要添加test-while-idle等参数来解决连接关闭问题?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/888490.html
微信扫一扫
支付宝扫一扫