mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
fix: SSE心跳保活机制,防止后端重启后连接死掉无法感知
后端: - 每15秒向SSE连接发送ping事件 - emitter关闭/超时时取消心跳任务 - 连接断开时自动清理心跳 前端: - 监听ping事件更新lastPingTime - 每5秒检测一次,超过20秒没收到ping则断开重连
This commit is contained in:
+1
-1
@@ -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);
|
||||
|
||||
+83
-6
@@ -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<Long, SseEmitter> userConnections = new ConcurrentHashMap<>();
|
||||
private final Map<Long, ScheduledFuture<?>> 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<String, Object> 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<String, Object> 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<ImportTaskPO> 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 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
||||
null,
|
||||
);
|
||||
const sseConnected = ref(false);
|
||||
// 心跳检测:上次收到ping的时间
|
||||
const lastPingTime = ref<number | null>(null);
|
||||
let pingCheckTimer: ReturnType<typeof setInterval> | 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user