From 2b35471debfe096f94be13c6fd502716e333c836 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E8=9F=91=E8=9E=82?= Date: Thu, 16 Apr 2026 13:43:11 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20SSE=E5=BF=83=E8=B7=B3=E4=BF=9D=E6=B4=BB?= =?UTF-8?q?=E6=9C=BA=E5=88=B6=EF=BC=8C=E9=98=B2=E6=AD=A2=E5=90=8E=E7=AB=AF?= =?UTF-8?q?=E9=87=8D=E5=90=AF=E5=90=8E=E8=BF=9E=E6=8E=A5=E6=AD=BB=E6=8E=89?= =?UTF-8?q?=E6=97=A0=E6=B3=95=E6=84=9F=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端: - 每15秒向SSE连接发送ping事件 - emitter关闭/超时时取消心跳任务 - 连接断开时自动清理心跳 前端: - 监听ping事件更新lastPingTime - 每5秒检测一次,超过20秒没收到ping则断开重连 --- .../service/impl/OrderImportProcessor.java | 2 +- .../impl/SseNotificationServiceImpl.java | 89 +++++++++++++++++-- .../apps/web-antd/src/store/import-task.ts | 28 ++++++ 3 files changed, 112 insertions(+), 7 deletions(-) diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java index 21a4509c..ed41ae18 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java @@ -262,7 +262,7 @@ public class OrderImportProcessor { .append(System.lineSeparator()); } - if ((i + 1) % 1000 == 0 || (i + 1) == records.size()) { + if ((i + 1) % 100 == 0 || (i + 1) == records.size()) { result.successCount = i + 1 - result.failCount; if (progressCallback != null) { progressCallback.accept(result.totalCount, result.successCount); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/SseNotificationServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/SseNotificationServiceImpl.java index 77ce86e3..96f96940 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/SseNotificationServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/SseNotificationServiceImpl.java @@ -12,7 +12,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotification import java.io.IOException; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.*; /** * SSE通知服务实现类 @@ -22,13 +22,22 @@ public class SseNotificationServiceImpl implements SseNotificationService { private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class); + private static final long HEARTBEAT_INTERVAL_SECONDS = 15; + private final Map userConnections = new ConcurrentHashMap<>(); + private final Map> heartbeatTasks = new ConcurrentHashMap<>(); private final ImportTaskService importTaskService; private final ObjectMapper objectMapper; + private final ScheduledExecutorService scheduler; public SseNotificationServiceImpl(ImportTaskService importTaskService, ObjectMapper objectMapper) { this.importTaskService = importTaskService; this.objectMapper = objectMapper; + this.scheduler = new ScheduledThreadPoolExecutor(2, r -> { + Thread t = new Thread(r, "sse-heartbeat"); + t.setDaemon(true); + return t; + }); } /** @@ -49,6 +58,12 @@ public class SseNotificationServiceImpl implements SseNotificationService { } } + // 取消旧的心跳任务 + ScheduledFuture oldTask = heartbeatTasks.remove(userId); + if (oldTask != null) { + oldTask.cancel(false); + } + // 创建新的SSE连接,超时时间30分钟 SseEmitter emitter = new SseEmitter(30 * 60 * 1000L); userConnections.put(userId, emitter); @@ -57,11 +72,19 @@ public class SseNotificationServiceImpl implements SseNotificationService { emitter.onCompletion(() -> { logger.info("SSE连接完成,userId: {}", userId); userConnections.remove(userId); + ScheduledFuture task = heartbeatTasks.remove(userId); + if (task != null) { + task.cancel(false); + } }); emitter.onTimeout(() -> { logger.info("SSE连接超时,userId: {}", userId); userConnections.remove(userId); + ScheduledFuture task = heartbeatTasks.remove(userId); + if (task != null) { + task.cancel(false); + } try { emitter.complete(); } catch (Exception e) { @@ -72,6 +95,10 @@ public class SseNotificationServiceImpl implements SseNotificationService { emitter.onError((ex) -> { logger.error("SSE连接错误,userId: {}", userId, ex); userConnections.remove(userId); + ScheduledFuture task = heartbeatTasks.remove(userId); + if (task != null) { + task.cancel(false); + } try { emitter.completeWithError(ex); } catch (Exception e) { @@ -93,10 +120,54 @@ public class SseNotificationServiceImpl implements SseNotificationService { emitter.completeWithError(e); } + // 启动心跳 + startHeartbeat(userId, emitter); + logger.info("创建SSE连接成功,userId: {}", userId); return emitter; } + /** + * 启动心跳 + */ + private void startHeartbeat(Long userId, SseEmitter emitter) { + ScheduledFuture task = scheduler.scheduleAtFixedRate(() -> { + SseEmitter currentEmitter = userConnections.get(userId); + if (currentEmitter == null || currentEmitter != emitter) { + // 连接已更换或不存在,取消心跳 + ScheduledFuture t = heartbeatTasks.remove(userId); + if (t != null) { + t.cancel(false); + } + return; + } + + try { + Map pingMessage = new java.util.HashMap<>(); + pingMessage.put("type", "ping"); + pingMessage.put("timestamp", System.currentTimeMillis()); + + currentEmitter.send(SseEmitter.event() + .name("ping") + .data(objectMapper.writeValueAsString(pingMessage))); + } catch (IOException e) { + logger.debug("发送心跳失败,移除连接,userId: {}", userId); + userConnections.remove(userId); + ScheduledFuture t = heartbeatTasks.remove(userId); + if (t != null) { + t.cancel(false); + } + try { + currentEmitter.completeWithError(e); + } catch (Exception ex) { + // ignore + } + } + }, HEARTBEAT_INTERVAL_SECONDS, HEARTBEAT_INTERVAL_SECONDS, TimeUnit.SECONDS); + + heartbeatTasks.put(userId, task); + } + /** * 发送任务进度通知 * @@ -114,7 +185,7 @@ public class SseNotificationServiceImpl implements SseNotificationService { try { Map progressMessage = new java.util.HashMap<>(); progressMessage.put("type", "task_progress"); - progressMessage.put("task", taskVO); // 发送完整的ImportTaskVO + progressMessage.put("task", taskVO); emitter.send(SseEmitter.event() .name("task_progress") @@ -130,6 +201,10 @@ public class SseNotificationServiceImpl implements SseNotificationService { } catch (IOException e) { logger.error("发送任务进度通知失败,userId: {}, taskId: {}", userId, taskVO != null ? taskVO.getId() : null, e); userConnections.remove(userId); + ScheduledFuture task = heartbeatTasks.remove(userId); + if (task != null) { + task.cancel(false); + } try { emitter.completeWithError(e); } catch (Exception ex) { @@ -146,6 +221,10 @@ public class SseNotificationServiceImpl implements SseNotificationService { @Override public void closeConnection(Long userId) { SseEmitter emitter = userConnections.remove(userId); + ScheduledFuture task = heartbeatTasks.remove(userId); + if (task != null) { + task.cancel(false); + } if (emitter != null) { try { emitter.complete(); @@ -164,7 +243,6 @@ public class SseNotificationServiceImpl implements SseNotificationService { */ @Override public boolean hasActiveTasks(Long userId) { - // 查询用户是否有pending或processing状态的任务 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); wrapper.eq(ImportTaskPO::getCreateBy, userId) @@ -174,7 +252,7 @@ public class SseNotificationServiceImpl implements SseNotificationService { } /** - * 通知所有任务已完成,可以关闭连接 + * 通知所有任务已完成 * * @param userId 用户ID */ @@ -195,7 +273,7 @@ public class SseNotificationServiceImpl implements SseNotificationService { .data(objectMapper.writeValueAsString(completeMessage))); logger.info("通知所有任务已完成,userId: {}", userId); - // 不再主动关闭连接,让SSE保持长连接,前端持续接收任务更新 + // 不再主动关闭连接,让SSE保持长连接 } catch (IOException e) { logger.error("通知所有任务完成失败,userId: {}", userId, e); @@ -213,4 +291,3 @@ public class SseNotificationServiceImpl implements SseNotificationService { } } } - diff --git a/ecom-dmb-frontend/apps/web-antd/src/store/import-task.ts b/ecom-dmb-frontend/apps/web-antd/src/store/import-task.ts index e5dccbc2..e2cc5e81 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/store/import-task.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/store/import-task.ts @@ -29,6 +29,9 @@ export const useImportTaskStore = defineStore('import-task', () => { null, ); const sseConnected = ref(false); + // 心跳检测:上次收到ping的时间 + const lastPingTime = ref(null); + let pingCheckTimer: ReturnType | null = null; // 加载状态 const loading = ref(false); @@ -165,6 +168,21 @@ export const useImportTaskStore = defineStore('import-task', () => { connection.connect(); + // 启动心跳检测:每5秒检查一次,超过20秒没收到ping则断开重连 + lastPingTime.value = Date.now(); + if (pingCheckTimer !== null) { + clearInterval(pingCheckTimer); + } + pingCheckTimer = setInterval(() => { + if (lastPingTime.value !== null && Date.now() - lastPingTime.value > 20_000) { + console.warn('SSE心跳超时,断开并重连'); + disconnectSse(); + setTimeout(() => { + connectSse(); + }, 1000); + } + }, 5_000); + // 连接成功(如果不在等待连接,则正常处理) connection.addEventListener('message', (event) => { try { @@ -177,6 +195,11 @@ export const useImportTaskStore = defineStore('import-task', () => { } }); + // 接收心跳ping + connection.addEventListener('ping', () => { + lastPingTime.value = Date.now(); + }); + // 接收任务进度更新 connection.addEventListener('task_progress', (event) => { try { @@ -226,6 +249,11 @@ export const useImportTaskStore = defineStore('import-task', () => { sseConnection.value.disconnect(); sseConnection.value = null; sseConnected.value = false; + lastPingTime.value = null; + } + if (pingCheckTimer !== null) { + clearInterval(pingCheckTimer); + pingCheckTimer = null; } }