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分钟

相关推荐
浮尘笔记18 小时前
Go语言临时对象池:sync.Pool的原理与使用
开发语言·后端·golang
梦梦代码精19 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
REDcker20 小时前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
没有bug.的程序员1 天前
Java 序列化:Serializable vs. Protobuf 的性能与兼容性深度对比
java·开发语言·后端·反射·序列化·serializable·protobuf
我爱娃哈哈1 天前
SpringBoot + Spring Security + RBAC:企业级权限模型设计与动态菜单渲染实战
spring boot·后端·spring
小王不爱笑1321 天前
SpringBoot 配置文件
java·spring boot·后端
想用offer打牌1 天前
Spring AI vs Spring AI Alibaba
java·人工智能·后端·spring·系统架构
码农幻想梦1 天前
实验五 spring入门及IOC实验
java·后端·spring
a程序小傲1 天前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
派大鑫wink1 天前
【Day39】Spring 核心注解:@Component、@Autowired、@Configuration 等
java·后端·spring