mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03:49:19 +08:00
fix: SSE多设备连接修复(token刷新+deviceId隔离)
This commit is contained in:
+6
-1
@@ -5,6 +5,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
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.bind.annotation.RestController;
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
@@ -31,8 +32,12 @@ public class ImportTaskSseController {
|
|||||||
@Operation(summary = "建立SSE连接", description = "前端在创建任务前建立SSE连接,用于接收任务进度推送")
|
@Operation(summary = "建立SSE连接", description = "前端在创建任务前建立SSE连接,用于接收任务进度推送")
|
||||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
@RequirePermission(value = "data:import", description = "建立SSE连接", allowSuper = true)
|
@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();
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
|
if (deviceId == null || deviceId.trim().isEmpty()) {
|
||||||
return sseNotificationService.createConnection(userId);
|
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 {
|
public interface SseNotificationService {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建SSE连接
|
* 创建SSE连接(兼容旧调用,无设备标识)
|
||||||
*
|
*
|
||||||
* @param userId 用户ID
|
* @param userId 用户ID
|
||||||
* @return SSE发射器
|
* @return SSE发射器
|
||||||
*/
|
*/
|
||||||
SseEmitter createConnection(Long userId);
|
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);
|
void notifyAllTasksCompleted(Long userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+293
-214
@@ -11,21 +11,51 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskServi
|
|||||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
|
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SSE通知服务实现类
|
* SSE通知服务实现类(多设备版本)
|
||||||
|
*
|
||||||
|
* 架构:Map(userId → List(EmitterWithDevice))
|
||||||
|
* - 一个用户可有多个设备/标签页同时连接
|
||||||
|
* - deviceId 去重:新连接同 deviceId 则关掉旧连接
|
||||||
|
* - 单用户最大连接数:10(超出则踢最旧的)
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class SseNotificationServiceImpl implements SseNotificationService {
|
public class SseNotificationServiceImpl implements SseNotificationService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class);
|
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 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 Map<Long, ScheduledFuture<?>> heartbeatTasks = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private final ImportTaskService importTaskService;
|
private final ImportTaskService importTaskService;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
private final ScheduledExecutorService scheduler;
|
private final ScheduledExecutorService scheduler;
|
||||||
@@ -40,254 +70,303 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== 连接管理 ====================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建SSE连接
|
* 兼容旧调用:自动生成匿名 deviceId
|
||||||
*
|
|
||||||
* @param userId 用户ID
|
|
||||||
* @return SSE发射器
|
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public SseEmitter createConnection(Long userId) {
|
public SseEmitter createConnection(Long userId) {
|
||||||
// 如果已存在连接,先关闭
|
return createConnection(userId, "device-" + System.nanoTime());
|
||||||
SseEmitter existingEmitter = userConnections.get(userId);
|
}
|
||||||
if (existingEmitter != null) {
|
|
||||||
|
/**
|
||||||
|
* 创建/重建 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 创建新 emitter
|
||||||
|
SseEmitter emitter = new SseEmitter(SSE_TIMEOUT_MS);
|
||||||
|
EmitterEntry newEntry = new EmitterEntry(deviceId, emitter);
|
||||||
|
entries.add(newEntry);
|
||||||
|
|
||||||
|
// 4. 注册回调
|
||||||
|
registerCallbacks(userId, deviceId, entries, emitter, newEntry);
|
||||||
|
|
||||||
|
// 5. 发送初始消息
|
||||||
try {
|
try {
|
||||||
existingEmitter.complete();
|
Map<String, Object> msg = Map.of(
|
||||||
} catch (Exception e) {
|
"type", "connected",
|
||||||
logger.warn("关闭已存在的SSE连接失败,userId: {}", userId, e);
|
"message", "SSE连接已建立",
|
||||||
}
|
"deviceId", deviceId
|
||||||
}
|
);
|
||||||
|
|
||||||
// 取消旧的心跳任务
|
|
||||||
ScheduledFuture<?> oldTask = heartbeatTasks.remove(userId);
|
|
||||||
if (oldTask != null) {
|
|
||||||
oldTask.cancel(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建新的SSE连接,超时时间30分钟
|
|
||||||
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
|
|
||||||
userConnections.put(userId, emitter);
|
|
||||||
|
|
||||||
// 设置完成和超时回调
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 发送初始连接成功消息
|
|
||||||
try {
|
|
||||||
Map<String, Object> initialMessage = new java.util.HashMap<>();
|
|
||||||
initialMessage.put("type", "connected");
|
|
||||||
initialMessage.put("message", "SSE连接已建立");
|
|
||||||
emitter.send(SseEmitter.event()
|
emitter.send(SseEmitter.event()
|
||||||
.name("message")
|
.name("message")
|
||||||
.data(objectMapper.writeValueAsString(initialMessage)));
|
.data(objectMapper.writeValueAsString(msg)));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("发送初始SSE消息失败,userId: {}", userId, e);
|
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, deviceId, e);
|
||||||
userConnections.remove(userId);
|
entries.remove(newEntry);
|
||||||
emitter.completeWithError(e);
|
safeComplete(emitter);
|
||||||
}
|
|
||||||
|
|
||||||
// 启动心跳
|
|
||||||
startHeartbeat(userId, emitter);
|
|
||||||
|
|
||||||
logger.info("创建SSE连接成功,userId: {}", userId);
|
|
||||||
return emitter;
|
return emitter;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// 6. 启动/重启心跳
|
||||||
* 启动心跳
|
ensureHeartbeatRunning(userId);
|
||||||
*/
|
|
||||||
private void startHeartbeat(Long userId, SseEmitter emitter) {
|
return 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 {
|
private void registerCallbacks(Long userId, String deviceId,
|
||||||
Map<String, Object> pingMessage = new java.util.HashMap<>();
|
List<EmitterEntry> entries,
|
||||||
pingMessage.put("type", "ping");
|
SseEmitter emitter, EmitterEntry entry) {
|
||||||
pingMessage.put("timestamp", System.currentTimeMillis());
|
emitter.onCompletion(() -> {
|
||||||
|
logger.info("SSE连接完成,userId={}, deviceId={}", userId, deviceId);
|
||||||
|
entries.remove(entry);
|
||||||
|
cleanupIfEmpty(userId, entries);
|
||||||
|
});
|
||||||
|
|
||||||
currentEmitter.send(SseEmitter.event()
|
emitter.onTimeout(() -> {
|
||||||
.name("ping")
|
logger.info("SSE连接超时,userId={}, deviceId={}", userId, deviceId);
|
||||||
.data(objectMapper.writeValueAsString(pingMessage)));
|
entries.remove(entry);
|
||||||
} catch (IOException e) {
|
safeComplete(emitter);
|
||||||
logger.debug("发送心跳失败,移除连接,userId: {}", userId);
|
cleanupIfEmpty(userId, entries);
|
||||||
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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private void cleanupIfEmpty(Long userId, List<EmitterEntry> entries) {
|
||||||
* 发送任务进度通知
|
if (entries.isEmpty()) {
|
||||||
*
|
|
||||||
* @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);
|
|
||||||
userConnections.remove(userId);
|
userConnections.remove(userId);
|
||||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||||
if (task != null) {
|
if (task != null) task.cancel(false);
|
||||||
task.cancel(false);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
emitter.completeWithError(e);
|
|
||||||
} catch (Exception ex) {
|
|
||||||
logger.warn("完成错误的SSE连接失败,userId: {}", userId, ex);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private EmitterEntry findEntry(List<EmitterEntry> entries, String deviceId) {
|
||||||
* 关闭用户的SSE连接
|
for (EmitterEntry e : entries) {
|
||||||
*
|
if (e.deviceId.equals(deviceId)) return e;
|
||||||
* @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);
|
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void safeComplete(SseEmitter emitter) {
|
||||||
if (emitter != null) {
|
if (emitter != null) {
|
||||||
try {
|
try {
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
logger.info("关闭SSE连接成功,userId: {}", userId);
|
} 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) {
|
} catch (Exception e) {
|
||||||
logger.warn("关闭SSE连接失败,userId: {}", userId, 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// ==================== 发送消息 ====================
|
||||||
* 检查用户是否有活跃的任务
|
|
||||||
*
|
@Override
|
||||||
* @param userId 用户ID
|
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||||
* @return 是否有活跃任务
|
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
|
@Override
|
||||||
public boolean hasActiveTasks(Long userId) {
|
public boolean hasActiveTasks(Long userId) {
|
||||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||||
long count = importTaskService.count(wrapper);
|
return importTaskService.count(wrapper) > 0;
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,18 +38,26 @@ export async function getImportTaskPageApi(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SSE连接管理器(使用原生EventSource,支持自动重连)
|
* SSE连接管理器(使用原生EventSource,支持多设备和 token 刷新重连)
|
||||||
*/
|
*/
|
||||||
class SseConnection {
|
class SseConnection {
|
||||||
private eventSource: EventSource | null = null;
|
private eventSource: EventSource | null = null;
|
||||||
private accessStore: ReturnType<typeof useAccessStore>;
|
|
||||||
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
||||||
new Map();
|
new Map();
|
||||||
// EventSource 原生状态常量
|
// EventSource 原生状态常量
|
||||||
private readyState: number = EventSource.CLOSED;
|
private readyState: number = EventSource.CLOSED;
|
||||||
|
/** 设备标识,同一标签页内共用,重开标签页是新ID */
|
||||||
|
private deviceId: string;
|
||||||
|
|
||||||
|
/** 设备标识,每个标签页独立,不跨标签页共享 */
|
||||||
|
private deviceId: string;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.accessStore = useAccessStore();
|
// 每个 SseConnection 实例独立生成 deviceId
|
||||||
|
// 不存 sessionStorage:同 origin 不同标签页不应共享 ID
|
||||||
|
this.deviceId = crypto.randomUUID
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -88,13 +96,17 @@ class SseConnection {
|
|||||||
this.disconnect();
|
this.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = this.accessStore.accessToken;
|
// token 必须由调用方传入(connectSse 在重连前已刷新 token)
|
||||||
|
const accessStore = useAccessStore();
|
||||||
|
const token = accessStore.accessToken;
|
||||||
if (!token) {
|
if (!token) {
|
||||||
console.error('无法建立SSE连接:token不存在');
|
console.error('无法建立SSE连接:token不存在');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}`;
|
// 加时间戳参数避免浏览器复用/合并同 URL 的 EventSource 连接
|
||||||
|
const ts = Date.now();
|
||||||
|
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}&deviceId=${encodeURIComponent(this.deviceId)}&t=${ts}`;
|
||||||
this.readyState = EventSource.CONNECTING;
|
this.readyState = EventSource.CONNECTING;
|
||||||
|
|
||||||
const es = new EventSource(url);
|
const es = new EventSource(url);
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ import type { PageQueryDTO } from '#/types/common';
|
|||||||
|
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
|
|
||||||
|
import { useAccessStore } from '@vben/stores';
|
||||||
import { defineStore } from 'pinia';
|
import { defineStore } from 'pinia';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
createSseConnection,
|
createSseConnection,
|
||||||
getImportTaskPageApi,
|
getImportTaskPageApi,
|
||||||
} from '#/api/ecommerce/import-task';
|
} from '#/api/ecommerce/import-task';
|
||||||
|
import { requestClient } from '#/api/request';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 导入任务管理 Store
|
* 导入任务管理 Store
|
||||||
@@ -32,6 +34,8 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
// 心跳检测:上次收到ping的时间
|
// 心跳检测:上次收到ping的时间
|
||||||
const lastPingTime = ref<number | null>(null);
|
const lastPingTime = ref<number | null>(null);
|
||||||
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
|
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
// 页面可见性监听器引用
|
||||||
|
let visibilityHandler: (() => void) | null = null;
|
||||||
|
|
||||||
// 加载状态
|
// 加载状态
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
@@ -104,29 +108,71 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 建立SSE连接
|
* 确保持有有效的 access token
|
||||||
* @returns Promise,连接建立成功后resolve
|
*
|
||||||
|
* 逻辑:
|
||||||
|
* 1. 如果 refreshToken 已过期 → 返回 null(需重新登录)
|
||||||
|
* 2. 如果 accessToken 未过期且未接近过期 → 直接返回
|
||||||
|
* 3. 如果 accessToken 快过期或已过期 → 发一个轻量请求,
|
||||||
|
* requestClient 会自动刷新 token,等待刷新完成后返回新 token
|
||||||
|
*
|
||||||
|
* @returns 有效 token,null 表示 refreshToken 已过期无法刷新
|
||||||
*/
|
*/
|
||||||
function connectSse(): Promise<void> {
|
async function ensureValidToken(): Promise<string | null> {
|
||||||
return new Promise((resolve, reject) => {
|
const accessStore = useAccessStore();
|
||||||
// 如果已经连接且已连接成功,直接resolve
|
|
||||||
|
// refreshToken 已过期,无法刷新
|
||||||
|
if (accessStore.isRefreshTokenExpired()) {
|
||||||
|
console.warn('[SSE] refreshToken 已过期,无法刷新 token,SSE 将不建立连接');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// accessToken 仍然有效且未接近过期,直接返回
|
||||||
|
if (!accessStore.isAccessTokenExpiringSoon()) {
|
||||||
|
return accessStore.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
// accessToken 快过期或已过期,通过 requestClient 触发刷新
|
||||||
|
// 随便发一个轻量请求,走 requestClient 的 401 拦截器自动刷新
|
||||||
|
try {
|
||||||
|
await requestClient.get('/auth/current/userinfo');
|
||||||
|
} catch {
|
||||||
|
// 刷新失败,ignore(requestClient 已处理)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刷新后检查
|
||||||
|
if (accessStore.isRefreshTokenExpired()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return accessStore.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建立SSE连接(连接前自动确保 token 有效)
|
||||||
|
*
|
||||||
|
* @returns Promise,连接建立成功后 resolve
|
||||||
|
*/
|
||||||
|
async function connectSse(): Promise<void> {
|
||||||
|
// 如果已经连接且已连接成功,直接返回
|
||||||
if (sseConnection.value && sseConnected.value) {
|
if (sseConnection.value && sseConnected.value) {
|
||||||
resolve();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果已经连接但未成功,先关闭
|
// 确保 token 有效(可能触发刷新)
|
||||||
if (sseConnection.value) {
|
const token = await ensureValidToken();
|
||||||
disconnectSse();
|
if (!token) {
|
||||||
|
console.warn('[SSE] token 无效,无法建立连接');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 关闭旧连接
|
||||||
|
disconnectSse();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const connection = createSseConnection();
|
const connection = createSseConnection();
|
||||||
sseConnection.value = connection;
|
sseConnection.value = connection;
|
||||||
sseConnected.value = false;
|
sseConnected.value = false;
|
||||||
|
|
||||||
let timeoutId: null | ReturnType<typeof setTimeout> = null;
|
|
||||||
|
|
||||||
// 监听连接成功事件
|
// 监听连接成功事件
|
||||||
const connectedHandler = (event: MessageEvent) => {
|
const connectedHandler = (event: MessageEvent) => {
|
||||||
try {
|
try {
|
||||||
@@ -134,38 +180,24 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
if (data.type === 'connected') {
|
if (data.type === 'connected') {
|
||||||
sseConnected.value = true;
|
sseConnected.value = true;
|
||||||
connection.removeEventListener('message', connectedHandler);
|
connection.removeEventListener('message', connectedHandler);
|
||||||
if (timeoutId) {
|
|
||||||
clearTimeout(timeoutId);
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略解析错误,继续等待
|
// 忽略解析错误
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 监听连接错误
|
// 连接失败(拒绝 Promise)
|
||||||
const errorHandler = (_event: MessageEvent) => {
|
const errorHandler = (_event: MessageEvent) => {
|
||||||
connection.removeEventListener('message', connectedHandler);
|
connection.removeEventListener('message', connectedHandler);
|
||||||
connection.removeEventListener('error', errorHandler);
|
connection.removeEventListener('error', errorHandler);
|
||||||
if (timeoutId) {
|
sseConnected.value = false;
|
||||||
clearTimeout(timeoutId);
|
// 安排重连(会重新检查并刷新 token)
|
||||||
}
|
scheduleReconnect(5000);
|
||||||
reject(new Error('SSE连接失败'));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
connection.addEventListener('message', connectedHandler);
|
connection.addEventListener('message', connectedHandler);
|
||||||
connection.addEventListener('error', errorHandler);
|
connection.addEventListener('error', errorHandler);
|
||||||
|
|
||||||
// 设置超时,避免无限等待
|
|
||||||
timeoutId = setTimeout(() => {
|
|
||||||
if (!sseConnected.value) {
|
|
||||||
connection.removeEventListener('message', connectedHandler);
|
|
||||||
connection.removeEventListener('error', errorHandler);
|
|
||||||
reject(new Error('SSE连接超时'));
|
|
||||||
}
|
|
||||||
}, 10_000); // 10秒超时
|
|
||||||
|
|
||||||
connection.connect();
|
connection.connect();
|
||||||
|
|
||||||
// 启动心跳检测:每5秒检查一次,超过20秒没收到ping则断开重连
|
// 启动心跳检测:每5秒检查一次,超过20秒没收到ping则断开重连
|
||||||
@@ -175,25 +207,20 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
}
|
}
|
||||||
pingCheckTimer = setInterval(() => {
|
pingCheckTimer = setInterval(() => {
|
||||||
if (lastPingTime.value !== null && Date.now() - lastPingTime.value > 20_000) {
|
if (lastPingTime.value !== null && Date.now() - lastPingTime.value > 20_000) {
|
||||||
console.warn('SSE心跳超时,断开并重连');
|
console.warn('[SSE] 心跳超时,断开并重连');
|
||||||
disconnectSse();
|
scheduleReconnect(1000);
|
||||||
setTimeout(() => {
|
|
||||||
connectSse();
|
|
||||||
}, 1000);
|
|
||||||
}
|
}
|
||||||
}, 5_000);
|
}, 5_000);
|
||||||
|
|
||||||
// 连接成功(如果不在等待连接,则正常处理)
|
// 监听页面可见性变化:切回前台时重连(token 可能已刷新)
|
||||||
connection.addEventListener('message', (event) => {
|
if (visibilityHandler === null) {
|
||||||
try {
|
visibilityHandler = () => {
|
||||||
const data = JSON.parse(event.data);
|
if (document.visibilityState === 'visible') {
|
||||||
if (data.type === 'connected') {
|
scheduleReconnect(1000);
|
||||||
sseConnected.value = true;
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
};
|
||||||
console.error('解析SSE消息失败:', error);
|
document.addEventListener('visibilitychange', visibilityHandler);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
// 接收心跳ping
|
// 接收心跳ping
|
||||||
connection.addEventListener('ping', () => {
|
connection.addEventListener('ping', () => {
|
||||||
@@ -215,46 +242,58 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
// 所有任务完成
|
// 所有任务完成
|
||||||
connection.addEventListener('all_tasks_completed', () => {
|
connection.addEventListener('all_tasks_completed', () => {
|
||||||
try {
|
try {
|
||||||
// 刷新任务列表
|
|
||||||
fetchTasks(true);
|
fetchTasks(true);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('刷新任务列表失败:', error);
|
console.error('刷新任务列表失败:', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 连接错误
|
|
||||||
connection.addEventListener('error', (event) => {
|
|
||||||
console.error('SSE连接错误:', event);
|
|
||||||
sseConnected.value = false;
|
|
||||||
// 如果连接关闭,无条件重连,不判断活跃任务
|
|
||||||
if (connection.getReadyState() === EventSource.CLOSED) {
|
|
||||||
setTimeout(() => {
|
|
||||||
connectSse();
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('建立SSE连接失败:', error);
|
console.error('建立SSE连接失败:', error);
|
||||||
sseConnected.value = false;
|
sseConnected.value = false;
|
||||||
reject(error);
|
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 延迟重连(重连前会刷新 token)
|
||||||
|
*/
|
||||||
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
function scheduleReconnect(delayMs: number) {
|
||||||
|
// 取消待执行的重连
|
||||||
|
if (reconnectTimer !== null) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
// 先断开现有连接
|
||||||
|
disconnectSse();
|
||||||
|
reconnectTimer = setTimeout(() => {
|
||||||
|
reconnectTimer = null;
|
||||||
|
connectSse();
|
||||||
|
}, delayMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 断开SSE连接
|
* 断开SSE连接
|
||||||
*/
|
*/
|
||||||
function disconnectSse() {
|
function disconnectSse() {
|
||||||
if (sseConnection.value) {
|
if (reconnectTimer !== null) {
|
||||||
sseConnection.value.disconnect();
|
clearTimeout(reconnectTimer);
|
||||||
sseConnection.value = null;
|
reconnectTimer = null;
|
||||||
sseConnected.value = false;
|
|
||||||
lastPingTime.value = null;
|
|
||||||
}
|
}
|
||||||
if (pingCheckTimer !== null) {
|
if (pingCheckTimer !== null) {
|
||||||
clearInterval(pingCheckTimer);
|
clearInterval(pingCheckTimer);
|
||||||
pingCheckTimer = null;
|
pingCheckTimer = null;
|
||||||
}
|
}
|
||||||
|
if (visibilityHandler !== null) {
|
||||||
|
document.removeEventListener('visibilitychange', visibilityHandler);
|
||||||
|
visibilityHandler = null;
|
||||||
|
}
|
||||||
|
if (sseConnection.value) {
|
||||||
|
sseConnection.value.disconnect();
|
||||||
|
sseConnection.value = null;
|
||||||
|
}
|
||||||
|
sseConnected.value = false;
|
||||||
|
lastPingTime.value = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -262,8 +301,7 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
|||||||
*/
|
*/
|
||||||
async function init() {
|
async function init() {
|
||||||
await fetchTasks(true);
|
await fetchTasks(true);
|
||||||
|
// 页面加载时建立SSE连接,接收实时任务状态更新
|
||||||
// 页面加载时无条件建立SSE连接,接收实时任务状态更新
|
|
||||||
connectSse();
|
connectSse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user