From 6f94cf9c843756d91d59db25fed6ce804a1ccf50 Mon Sep 17 00:00:00 2001 From: "Ray.Hao" <1490493387@qq.com> Date: Thu, 2 Apr 2026 23:35:37 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20SSE=E8=BF=9E=E6=8E=A5=E9=98=BB=E5=A1=9E?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=85=B3=E9=97=AD=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?@PreDestroy=E4=BC=98=E9=9B=85=E6=96=AD=E5=BC=80=E6=89=80?= =?UTF-8?q?=E6=9C=89=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../message/registry/SseSessionRegistry.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/java/com/youlai/boot/message/registry/SseSessionRegistry.java b/src/main/java/com/youlai/boot/message/registry/SseSessionRegistry.java index ecbbe3fc..706f23d7 100644 --- a/src/main/java/com/youlai/boot/message/registry/SseSessionRegistry.java +++ b/src/main/java/com/youlai/boot/message/registry/SseSessionRegistry.java @@ -1,6 +1,7 @@ package com.youlai.boot.message.registry; import com.youlai.boot.message.dto.OnlineUserDTO; +import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @@ -193,4 +194,26 @@ public class SseSessionRegistry { emitters.forEach(emitter -> sendEvent(emitter, eventName, data)); } } + + /** + * 容器关闭时主动断开所有 SSE 连接,避免阻塞应用停止 + */ + @PreDestroy + public void destroy() { + int count = emitterUserMap.size(); + if (count == 0) { + return; + } + log.info("应用关闭,主动断开 {} 个SSE连接...", count); + emitterUserMap.keySet().forEach(emitter -> { + try { + emitter.complete(); + } catch (Exception ignored) { + } + }); + userEmittersMap.clear(); + emitterUserMap.clear(); + emitterTimeMap.clear(); + log.info("所有SSE连接已断开"); + } }