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

在使用MyBatis进行数据库操作时,切换到多数据源配置后,可能会遇到"No operations allowed after connection closed"的错误。之前在单数据源环境下,这种问题并未出现过,也没有配置过类似test-while-idle=true的参数。那么,为什么在多数据源环境下需要这些配置呢?
在多数据源配置之前,单数据源的配置如下:
<code># 单数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/db1 spring.datasource.username=root spring.datasource.password=password</code>
切换到多数据源配置后,配置变成了:
<code># 多数据源配置 spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=password <p>spring.datasource.test1.url=jdbc:mysql://localhost:3306/db2 spring.datasource.test1.username=root spring.datasource.test1.password=password</code>
然而,在多数据源环境下,出现了"No operations allowed after connection closed"的错误。网上搜索发现,需要添加以下MyBatis相关的配置:
<code>spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000</code>
那么,添加这些配置是否能解决问题呢?为什么在单数据源环境下不需要这些配置?
是的,添加上述配置通常能解决这个问题,特别是这些关键参数:
<code>spring.datasource.primary.test-while-idle=true spring.datasource.primary.time-between-eviction-runs-millis=18000</code>
对于每个数据源,都需要类似配置:
<code># 主数据源 spring.datasource.primary.test-while-idle=true spring.datasource.primary.validation-query=SELECT 1</p><h1>测试数据源</h1><p>spring.datasource.test1.test-while-idle=true spring.datasource.test1.validation-query=SELECT 1</code>
test-while-idle=true:
validation-query:
time-between-eviction-runs-millis:
min-idle 和 max-idle:
多数据源环境下,某些数据源可能较少使用,导致连接长时间空闲。数据库服务器通常会关闭长时间空闲的连接(如MySQL默认8小时)。如果应用尝试使用这些已关闭的连接,就会出现"No operations allowed after connection closed"错误。
通过启用test-while-idle和设置validation-query,连接池会定期验证连接是否有效,及时关闭无效连接并创建新连接,从而避免使用已关闭的连接。
以上就是为什么在MyBatis多数据源配置下需要添加test-while-idle等参数来解决连接关闭问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号