mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
fix: SSE多设备连接修复(token刷新+deviceId隔离)
This commit is contained in:
+7
-2
@@ -5,6 +5,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
@@ -31,8 +32,12 @@ public class ImportTaskSseController {
|
||||
@Operation(summary = "建立SSE连接", description = "前端在创建任务前建立SSE连接,用于接收任务进度推送")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@RequirePermission(value = "data:import", description = "建立SSE连接", allowSuper = true)
|
||||
public SseEmitter connect() {
|
||||
public SseEmitter connect(
|
||||
@RequestParam(value = "deviceId", required = false) String deviceId) {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
return sseNotificationService.createConnection(userId);
|
||||
if (deviceId == null || deviceId.trim().isEmpty()) {
|
||||
return sseNotificationService.createConnection(userId);
|
||||
}
|
||||
return sseNotificationService.createConnection(userId, deviceId.trim());
|
||||
}
|
||||
}
|
||||
|
||||
+10
-2
@@ -9,13 +9,22 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.vo.ImportTaskVO;
|
||||
public interface SseNotificationService {
|
||||
|
||||
/**
|
||||
* 创建SSE连接
|
||||
* 创建SSE连接(兼容旧调用,无设备标识)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 创建SSE连接(多设备版本)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param deviceId 设备/标签页标识(用于多设备去重)
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId, String deviceId);
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
@@ -46,4 +55,3 @@ public interface SseNotificationService {
|
||||
*/
|
||||
void notifyAllTasksCompleted(Long userId);
|
||||
}
|
||||
|
||||
|
||||
+288
-209
@@ -11,21 +11,51 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskServi
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* SSE通知服务实现类
|
||||
* SSE通知服务实现类(多设备版本)
|
||||
*
|
||||
* 架构:Map(userId → List(EmitterWithDevice))
|
||||
* - 一个用户可有多个设备/标签页同时连接
|
||||
* - deviceId 去重:新连接同 deviceId 则关掉旧连接
|
||||
* - 单用户最大连接数:10(超出则踢最旧的)
|
||||
*/
|
||||
@Service
|
||||
public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class);
|
||||
|
||||
/** 单用户最大设备连接数 */
|
||||
private static final int MAX_DEVICES_PER_USER = 10;
|
||||
|
||||
/** SSE 超时时间:30 分钟 */
|
||||
private static final long SSE_TIMEOUT_MS = 30 * 60 * 1000L;
|
||||
|
||||
/** 心跳间隔:15 秒 */
|
||||
private static final long HEARTBEAT_INTERVAL_SECONDS = 15;
|
||||
|
||||
private final Map<Long, SseEmitter> userConnections = new ConcurrentHashMap<>();
|
||||
/** 设备元数据包装器 */
|
||||
private static class EmitterEntry {
|
||||
final String deviceId;
|
||||
final SseEmitter emitter;
|
||||
long lastHeartbeat;
|
||||
|
||||
EmitterEntry(String deviceId, SseEmitter emitter) {
|
||||
this.deviceId = deviceId;
|
||||
this.emitter = emitter;
|
||||
this.lastHeartbeat = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
/** userId → 该用户的所有设备连接 */
|
||||
private final Map<Long, List<EmitterEntry>> userConnections = new ConcurrentHashMap<>();
|
||||
/** userId → 心跳定时任务 */
|
||||
private final Map<Long, ScheduledFuture<?>> heartbeatTasks = new ConcurrentHashMap<>();
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
@@ -40,254 +70,303 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 连接管理 ====================
|
||||
|
||||
/**
|
||||
* 创建SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
* 兼容旧调用:自动生成匿名 deviceId
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId) {
|
||||
// 如果已存在连接,先关闭
|
||||
SseEmitter existingEmitter = userConnections.get(userId);
|
||||
if (existingEmitter != null) {
|
||||
try {
|
||||
existingEmitter.complete();
|
||||
} catch (Exception e) {
|
||||
logger.warn("关闭已存在的SSE连接失败,userId: {}", userId, e);
|
||||
return createConnection(userId, "device-" + System.nanoTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建/重建 SSE 连接(多设备版本)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param deviceId 设备标识(标签页 UUID)
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId, String deviceId) {
|
||||
logger.info("创建SSE连接,userId={}, deviceId={}", userId, deviceId);
|
||||
|
||||
List<EmitterEntry> entries = userConnections.computeIfAbsent(userId, k -> new ArrayList<>());
|
||||
|
||||
// 1. deviceId 去重:同设备的新连接覆盖旧的
|
||||
EmitterEntry existingEntry = findEntry(entries, deviceId);
|
||||
if (existingEntry != null) {
|
||||
logger.info("设备已存在连接,关闭旧连接,deviceId={}", deviceId);
|
||||
safeComplete(existingEntry.emitter);
|
||||
entries.remove(existingEntry);
|
||||
}
|
||||
|
||||
// 2. 超出上限,移除最旧的连接
|
||||
if (entries.size() >= MAX_DEVICES_PER_USER) {
|
||||
EmitterEntry oldest = entries.stream()
|
||||
.min((a, b) -> Long.compare(a.lastHeartbeat, b.lastHeartbeat))
|
||||
.orElse(null);
|
||||
if (oldest != null) {
|
||||
logger.info("设备数超限,移除最旧连接,deviceId={}", oldest.deviceId);
|
||||
safeComplete(oldest.emitter);
|
||||
entries.remove(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
// 取消旧的心跳任务
|
||||
ScheduledFuture<?> oldTask = heartbeatTasks.remove(userId);
|
||||
if (oldTask != null) {
|
||||
oldTask.cancel(false);
|
||||
}
|
||||
// 3. 创建新 emitter
|
||||
SseEmitter emitter = new SseEmitter(SSE_TIMEOUT_MS);
|
||||
EmitterEntry newEntry = new EmitterEntry(deviceId, emitter);
|
||||
entries.add(newEntry);
|
||||
|
||||
// 创建新的SSE连接,超时时间30分钟
|
||||
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
|
||||
userConnections.put(userId, emitter);
|
||||
// 4. 注册回调
|
||||
registerCallbacks(userId, deviceId, entries, emitter, newEntry);
|
||||
|
||||
// 设置完成和超时回调
|
||||
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) {
|
||||
logger.warn("完成超时的SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
});
|
||||
|
||||
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) {
|
||||
logger.warn("完成错误的SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
});
|
||||
|
||||
// 发送初始连接成功消息
|
||||
// 5. 发送初始消息
|
||||
try {
|
||||
Map<String, Object> initialMessage = new java.util.HashMap<>();
|
||||
initialMessage.put("type", "connected");
|
||||
initialMessage.put("message", "SSE连接已建立");
|
||||
Map<String, Object> msg = Map.of(
|
||||
"type", "connected",
|
||||
"message", "SSE连接已建立",
|
||||
"deviceId", deviceId
|
||||
);
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("message")
|
||||
.data(objectMapper.writeValueAsString(initialMessage)));
|
||||
.data(objectMapper.writeValueAsString(msg)));
|
||||
} catch (IOException e) {
|
||||
logger.error("发送初始SSE消息失败,userId: {}", userId, e);
|
||||
userConnections.remove(userId);
|
||||
emitter.completeWithError(e);
|
||||
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, deviceId, e);
|
||||
entries.remove(newEntry);
|
||||
safeComplete(emitter);
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 启动心跳
|
||||
startHeartbeat(userId, emitter);
|
||||
// 6. 启动/重启心跳
|
||||
ensureHeartbeatRunning(userId);
|
||||
|
||||
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;
|
||||
}
|
||||
private void registerCallbacks(Long userId, String deviceId,
|
||||
List<EmitterEntry> entries,
|
||||
SseEmitter emitter, EmitterEntry entry) {
|
||||
emitter.onCompletion(() -> {
|
||||
logger.info("SSE连接完成,userId={}, deviceId={}", userId, deviceId);
|
||||
entries.remove(entry);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
try {
|
||||
Map<String, Object> pingMessage = new java.util.HashMap<>();
|
||||
pingMessage.put("type", "ping");
|
||||
pingMessage.put("timestamp", System.currentTimeMillis());
|
||||
emitter.onTimeout(() -> {
|
||||
logger.info("SSE连接超时,userId={}, deviceId={}", userId, deviceId);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
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);
|
||||
emitter.onError((ex) -> {
|
||||
logger.error("SSE连接错误,userId={}, deviceId={}", userId, deviceId, ex);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
@Override
|
||||
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
SseEmitter emitter = userConnections.get(userId);
|
||||
if (emitter == null) {
|
||||
logger.debug("用户没有SSE连接,userId: {}", userId);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> progressMessage = new java.util.HashMap<>();
|
||||
progressMessage.put("type", "task_progress");
|
||||
progressMessage.put("task", taskVO);
|
||||
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("task_progress")
|
||||
.data(objectMapper.writeValueAsString(progressMessage)));
|
||||
|
||||
logger.debug("发送任务进度通知成功,userId: {}, taskId: {}, status: {}", userId, taskVO.getId(), taskVO.getStatus());
|
||||
|
||||
// 如果任务已完成(success或failed),检查是否所有任务都已完成
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
checkAndNotifyAllTasksCompleted(userId);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("发送任务进度通知失败,userId: {}, taskId: {}", userId, taskVO != null ? taskVO.getId() : null, e);
|
||||
private void cleanupIfEmpty(Long userId, List<EmitterEntry> entries) {
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) {
|
||||
task.cancel(false);
|
||||
}
|
||||
try {
|
||||
emitter.completeWithError(e);
|
||||
} catch (Exception ex) {
|
||||
logger.warn("完成错误的SSE连接失败,userId: {}", userId, ex);
|
||||
}
|
||||
if (task != null) task.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭用户的SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
@Override
|
||||
public void closeConnection(Long userId) {
|
||||
SseEmitter emitter = userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) {
|
||||
task.cancel(false);
|
||||
private EmitterEntry findEntry(List<EmitterEntry> entries, String deviceId) {
|
||||
for (EmitterEntry e : entries) {
|
||||
if (e.deviceId.equals(deviceId)) return e;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void safeComplete(SseEmitter emitter) {
|
||||
if (emitter != null) {
|
||||
try {
|
||||
emitter.complete();
|
||||
logger.info("关闭SSE连接成功,userId: {}", userId);
|
||||
} catch (Exception e) {
|
||||
logger.warn("关闭SSE连接失败,userId: {}", userId, e);
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 心跳 ====================
|
||||
|
||||
private void ensureHeartbeatRunning(Long userId) {
|
||||
// 已有任务就复用
|
||||
if (heartbeatTasks.containsKey(userId)) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
|
||||
ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(
|
||||
() -> heartbeatForUser(userId),
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
heartbeatTasks.put(userId, task);
|
||||
}
|
||||
|
||||
private void heartbeatForUser(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
Map<String, Object> pingMsg;
|
||||
try {
|
||||
pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("ping")
|
||||
.data(objectMapper.writeValueAsString(pingMsg)));
|
||||
entry.lastHeartbeat = System.currentTimeMillis();
|
||||
} catch (IOException e) {
|
||||
logger.debug("心跳发送失败,移除连接,userId={}, deviceId={}", userId, entry.deviceId);
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
// 移除失效连接
|
||||
if (!deadEntries.isEmpty()) {
|
||||
entries.removeAll(deadEntries);
|
||||
for (EmitterEntry de : deadEntries) {
|
||||
safeComplete(de.emitter);
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否有活跃的任务
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 是否有活跃任务
|
||||
*/
|
||||
// ==================== 发送消息 ====================
|
||||
|
||||
@Override
|
||||
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
logger.debug("用户没有SSE连接,userId={}", userId);
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
Map<String, Object> progressMsg;
|
||||
try {
|
||||
progressMsg = Map.of(
|
||||
"type", "task_progress",
|
||||
"task", taskVO
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("task_progress")
|
||||
.data(objectMapper.writeValueAsString(progressMsg)));
|
||||
} catch (IOException e) {
|
||||
logger.debug("发送任务进度失败,移除连接,userId={}, deviceId={}", userId, entry.deviceId);
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
handleDeadEntries(userId, entries, deadEntries);
|
||||
|
||||
// 任务完成时,检查是否所有任务都结束了
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
checkAndNotifyAllTasksCompleted(userId);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleDeadEntries(Long userId, List<EmitterEntry> entries, List<EmitterEntry> deadEntries) {
|
||||
if (deadEntries.isEmpty()) return;
|
||||
entries.removeAll(deadEntries);
|
||||
for (EmitterEntry de : deadEntries) {
|
||||
safeComplete(de.emitter);
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 批量通知 ====================
|
||||
|
||||
@Override
|
||||
public void notifyAllTasksCompleted(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
|
||||
Map<String, Object> msg;
|
||||
try {
|
||||
msg = Map.of(
|
||||
"type", "all_tasks_completed",
|
||||
"message", "所有任务已完成"
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("all_tasks_completed")
|
||||
.data(objectMapper.writeValueAsString(msg)));
|
||||
} catch (IOException e) {
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, entries, deadEntries);
|
||||
logger.info("通知所有任务已完成,userId={}", userId);
|
||||
}
|
||||
|
||||
private void checkAndNotifyAllTasksCompleted(Long userId) {
|
||||
if (!hasActiveTasks(userId)) {
|
||||
notifyAllTasksCompleted(userId);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 关闭连接 ====================
|
||||
|
||||
@Override
|
||||
public void closeConnection(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) task.cancel(false);
|
||||
if (entries != null) {
|
||||
for (EmitterEntry e : entries) {
|
||||
safeComplete(e.emitter);
|
||||
}
|
||||
}
|
||||
logger.info("关闭用户所有SSE连接,userId={}", userId);
|
||||
}
|
||||
|
||||
// ==================== 查询 ====================
|
||||
|
||||
@Override
|
||||
public boolean hasActiveTasks(Long userId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||
long count = importTaskService.count(wrapper);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知所有任务已完成
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
@Override
|
||||
public void notifyAllTasksCompleted(Long userId) {
|
||||
SseEmitter emitter = userConnections.get(userId);
|
||||
if (emitter == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> completeMessage = new java.util.HashMap<>();
|
||||
completeMessage.put("type", "all_tasks_completed");
|
||||
completeMessage.put("message", "所有任务已完成");
|
||||
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("all_tasks_completed")
|
||||
.data(objectMapper.writeValueAsString(completeMessage)));
|
||||
|
||||
logger.info("通知所有任务已完成,userId: {}", userId);
|
||||
// 不再主动关闭连接,让SSE保持长连接
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("通知所有任务完成失败,userId: {}", userId, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并通知所有任务已完成
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
private void checkAndNotifyAllTasksCompleted(Long userId) {
|
||||
if (!hasActiveTasks(userId)) {
|
||||
notifyAllTasksCompleted(userId);
|
||||
}
|
||||
return importTaskService.count(wrapper) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user