springboot报错:No operations allowed after connection closed

😕今天使用springboot写好一个接口,准备测试的时候,控制台打印了报错信息

从图中可以得到以下几个关键信息😎:

  1. 数据库连接池使用的是HikariCP
  2. Possibly consider using a shorter maxLifetime value.(可以考虑使用更短的最大存活时间。)
  3. 最关键的异常:ConnectionIsClosedException,表示连接数据库的Connection已经关闭了
  4. 报错原因:过长的空闲时间导致连接超时并关闭,从而引发 ConnectionIsClosedException 错误。

从依赖和官方文档都可以证明,确实使用了Hikari连接池

📄下面这段话引用自Springboot官方文档

Supported Connection Pools

Spring Boot uses the following algorithm for choosing a specific implementation:

  1. We prefer HikariCP for its performance and concurrency. If HikariCP is available, we always choose it.
  2. Otherwise, if the Tomcat pooling DataSource is available, we use it.
  3. Otherwise, if Commons DBCP2 is available, we use it.
  4. If none of HikariCP, Tomcat, and DBCP2 are available and if Oracle UCP is available, we use it.

If you use the spring-boot-starter-jdbc or spring-boot-starter-data-jpa "starters", you automatically get a dependency to HikariCP.

意思是说,Springboot会优先使用HikariCP作为连接池,如果它不可用,才会考虑使用Tomcat的连接池,然后才是Commons DBCP2、Oracle UCP

以下引用了Chatgpt的回答

在 Spring Boot 1.x 版本中,默认的数据库连接池是 Tomcat JDBC 连接池(tomcat-jdbc)。但是从 Spring Boot 2.x 开始,HikariCP 取代了 Tomcat JDBC 成为默认的连接池。这是因为 HikariCP 具有出色的性能和高效的连接管理,被广泛认为是目前最快速和最轻量级的连接池之一。想要明确地指定使用 Tomcat JDBC 连接池,可以在项目的配置文件中进行相应的配置。

😃整理了网上搜索到的大部分解决方案

  1. ⭐方案一(不推荐):将 spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver 改为 spring.datasource.driverClassName=com.mysql.jdbc.Driver ,不推荐,因为使用cj的连接速度比旧版的更快。

  2. ⭐方案二:MySQL5 之前的版本,修改连接配置中的 URL添加参数:autoReconnect=true

  3. ⭐方案三(不推荐):MySQL5 及以后的版本,需要修改 my.cnf (或者my.ini ) 文件,在 [mysqld] 后面添加上:

    ini 复制代码
    # n为自定义的时间,单位:秒
    wait_timeout = n
    interactive-timeout = n
  4. ⭐⭐⭐方案四:修改连接池配置,查阅HikariCP官方的Configuration文档。注意,HikariCP使用毫秒作为时间值

关于 maxLifetime

控制池中连接的最长生存期。正在使用的连接永远不会停用,只有在关闭时才会将其删除。强烈建议设置此值 ,并且它应该比任何数据库或基础结构施加的连接时间限制短几秒钟。值为 0 表示没有最大生存期(无限生存期),当然受 idleTimeout 设置的约束。允许的最小值为 30000 毫秒(30 秒)。默认值:1800000(30 分钟)

配置如下,设置 maxLifetime 为20分钟

相关推荐
想用offer打牌39 分钟前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX2 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了2 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法3 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte4 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行5 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple5 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东5 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble5 小时前
springboot的核心实现机制原理
java·spring boot·后端