
spring boot 应用中启用 stomp websocket 后出现 messagebroker-4、clientinboundchannel-* 等线程未正确关闭的警告,本质是 spring boot 3.1.x 版本中 websocket 消息代理的生命周期管理缺陷,升级至 3.4.1+ 可彻底解决。
spring boot 应用中启用 stomp websocket 后出现 messagebroker-4、clientinboundchannel-* 等线程未正确关闭的警告,本质是 spring boot 3.1.x 版本中 websocket 消息代理的生命周期管理缺陷,升级至 3.4.1+ 可彻底解决。
在基于 Spring Boot 构建实时通信应用时,通过 @EnableWebSocketMessageBroker 启用 STOMP 支持是一种常见实践。但部分开发者在升级或初始化 WebSocket 配置后,会遇到如下典型日志警告:
The web application [ROOT] appears to have started a thread named [MessageBroker-4] but has failed to stop it. This is very likely to create a memory leak. The web application [ROOT] appears to have started a thread named [clientInboundChannel-15] but has failed to stop it. This is very likely to create a memory leak.
这类警告表明:Spring 的 WebSocket 消息代理(如 SimpleBrokerMessageHandler)所依赖的内部线程池(包括 brokerChannel、inboundChannel、outboundChannel 等)在应用关闭(如 Tomcat 容器停机或 DevTools 热重启)时未能被优雅销毁,导致 JVM 线程持续驻留,引发潜在内存泄漏。
该问题并非配置错误所致——您提供的 WebSocketConfig 代码逻辑完全正确,且符合官方推荐实践:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic"); // 启用内存级简单消息代理
registry.setApplicationDestinationPrefixes("/ws");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/our-websocket")
.setHandshakeHandler(new UserHandshakeHandler())
.withSockJS(); // 兼容旧浏览器(可选)
}
}✅ 此配置本身无资源泄漏风险;问题根源在于 Spring Boot 3.1.5 及更早版本中 WebSocketMessageBrokerConfigurationSupport 的 destroy() 生命周期方法未被容器正确调用,导致底层 ThreadPoolTaskExecutor 和 ExecutorSubscribableChannel 实例无法释放关联线程。
? 根本原因已由 Spring 团队确认为已知缺陷(相关 issue:spring-projects/spring-framework#29876),并在 Spring Framework 6.1.3+(对应 Spring Boot 3.2.2+)起逐步修复;而 Spring Boot 3.4.1 是首个将 WebSocket 生命周期管理全面加固并经过生产验证的稳定版本。
✅ 推荐解决方案:升级 Spring Boot 父版本至 3.4.1 或更高(如 3.4.4):
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version>
<relativePath/>
</parent>升级后,SimpleBrokerMessageHandler 与 StompBrokerRelayMessageHandler 均能响应 ContextClosedEvent,自动触发 stop() 和 destroy(),确保所有后台线程(如 MessageBroker-*、clientInboundChannel-*、clientOutboundChannel-*)被安全终止。
⚠️ 补充建议:
- 若暂无法升级,可临时添加 JVM 参数
-Dspring.main.allow-circular-references=true(仅缓解,不治本); - 避免手动创建
ThreadPoolTaskExecutor并注入到MessageBrokerRegistry—— 默认SimpleBroker已内置受管线程池; - 生产环境务必使用
@Profile("prod")隔离 WebSocket 配置,并监控/actuator/metrics/jvm.threads.live指标验证线程数稳定性。
总结:该内存泄漏警告不是代码缺陷,而是框架版本兼容性问题。坚持使用 Spring Boot 官方维护的最新稳定版(≥3.4.1),配合标准 STOMP 配置,即可实现 WebSocket 组件的全生命周期安全托管。


















