mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
feat: 抽出sse实时连接服务,导入进度和同步进度共用公共sse连接
This commit is contained in:
+56
@@ -0,0 +1,56 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 全量同步进度推送到公司在线用户的 SSE 通道。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderFullSyncProgressPublisher {
|
||||
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
|
||||
public void publish(PddOrderFullSyncTaskPO task) {
|
||||
if (task == null || task.getCompanyId() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
PddOrderFullSyncTaskVO vo = toVo(task);
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.PDD_ORDER_FULL_SYNC_PROGRESS,
|
||||
"task", vo
|
||||
);
|
||||
realtimeSseService.sendToCompany(
|
||||
task.getCompanyId(),
|
||||
RealtimeSseEvents.PDD_ORDER_FULL_SYNC_PROGRESS,
|
||||
payload);
|
||||
} catch (Exception ignored) {
|
||||
// SSE 失败不影响同步主流程
|
||||
}
|
||||
}
|
||||
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
return PddOrderFullSyncTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
.totalDays(task.getTotalDays())
|
||||
.doneDays(task.getDoneDays())
|
||||
.failedDays(task.getFailedDays())
|
||||
.status(task.getStatus())
|
||||
.lastError(task.getLastError())
|
||||
.createTime(task.getCreateTime())
|
||||
.finishTime(task.getFinishTime())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+8
@@ -20,6 +20,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
|
||||
private final PddOrderFullSyncTaskMapper taskMapper;
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
private final PddOrderFullSyncProgressPublisher progressPublisher;
|
||||
|
||||
public void execute(PddSyncFullMessage message) {
|
||||
if (message.getTaskId() != null) {
|
||||
@@ -47,6 +48,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
|
||||
task.setFinishTime(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
|
||||
// 已成功天数之后的下一自然日(失败日未计入 doneDays,续跑会重试失败日)
|
||||
int done = task.getDoneDays() == null ? 0 : task.getDoneDays();
|
||||
@@ -56,25 +58,30 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
PddOrderFullSyncTaskPO latest = taskMapper.selectById(taskId);
|
||||
if (latest != null && PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(latest.getStatus())) {
|
||||
log.info("全量同步任务已取消,停止执行 taskId={}", taskId);
|
||||
progressPublisher.publish(latest);
|
||||
return;
|
||||
}
|
||||
task.setCurrentDate(day);
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
pddOrderSyncService.syncByConfirmDateForTask(
|
||||
task.getCompanyId(), task.getShopId(), day, task.getId());
|
||||
task.setDoneDays((task.getDoneDays() == null ? 0 : task.getDoneDays()) + 1);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
day = day.plusDays(1);
|
||||
}
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_SUCCESS);
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
} catch (Exception e) {
|
||||
log.error("全量同步任务失败 taskId={}", taskId, e);
|
||||
PddOrderFullSyncTaskPO latest = taskMapper.selectById(taskId);
|
||||
if (latest != null && PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(latest.getStatus())) {
|
||||
progressPublisher.publish(latest);
|
||||
return;
|
||||
}
|
||||
task.setFailedDays((task.getFailedDays() == null ? 0 : task.getFailedDays()) + 1);
|
||||
@@ -83,6 +90,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
? e.getMessage().substring(0, 500) : e.getMessage());
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -54,6 +54,7 @@ public class PddOrderFullSyncTaskService {
|
||||
private final PddOrderSyncPublisher syncPublisher;
|
||||
private final PddOrderSyncProperties syncProperties;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PddOrderFullSyncProgressPublisher progressPublisher;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PddOrderFullSyncTaskVO createTask(PddOrderFullSyncTaskCreateDTO dto) {
|
||||
@@ -88,6 +89,7 @@ public class PddOrderFullSyncTaskService {
|
||||
syncPublisher.publishFullTask(
|
||||
task.getId(), task.getCompanyId(), task.getShopId(),
|
||||
task.getDateFrom(), task.getDateTo());
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
@@ -146,6 +148,7 @@ public class PddOrderFullSyncTaskService {
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
@@ -170,6 +173,7 @@ public class PddOrderFullSyncTaskService {
|
||||
syncPublisher.publishFullTask(
|
||||
task.getId(), task.getCompanyId(), task.getShopId(),
|
||||
task.getDateFrom(), task.getDateTo());
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 导入任务SSE控制器
|
||||
*/
|
||||
@Tag(name = "电商-导入任务SSE", description = "导入任务实时进度推送接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/import-task/sse")
|
||||
public class ImportTaskSseController {
|
||||
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ImportTaskSseController(SseNotificationService sseNotificationService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@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(
|
||||
@RequestParam(value = "deviceId", required = false) String deviceId) {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (deviceId == null || deviceId.trim().isEmpty()) {
|
||||
return sseNotificationService.createConnection(userId);
|
||||
}
|
||||
return sseNotificationService.createConnection(userId, deviceId.trim());
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.service;
|
||||
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
|
||||
/**
|
||||
* SSE通知服务接口
|
||||
*/
|
||||
public interface SseNotificationService {
|
||||
|
||||
/**
|
||||
* 创建SSE连接(兼容旧调用,无设备标识)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 创建SSE连接(多设备版本)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param deviceId 设备/标签页标识(用于多设备去重)
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId, String deviceId);
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
void sendTaskProgress(Long userId, ImportTaskVO taskVO);
|
||||
|
||||
/**
|
||||
* 关闭用户的SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void closeConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 检查用户是否有活跃的任务
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 是否有活跃任务
|
||||
*/
|
||||
boolean hasActiveTasks(Long userId);
|
||||
|
||||
/**
|
||||
* 通知所有任务已完成,可以关闭连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void notifyAllTasksCompleted(Long userId);
|
||||
}
|
||||
+28
-5
@@ -12,7 +12,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
@@ -49,7 +50,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OssService ossService;
|
||||
private final SysFileService sysFileService;
|
||||
@@ -66,7 +67,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
OrderItemMapper orderItemMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopProductRelationMapper shopProductRelationMapper,
|
||||
SseNotificationService sseNotificationService,
|
||||
RealtimeSseService realtimeSseService,
|
||||
ObjectMapper objectMapper,
|
||||
SqlSessionFactory sqlSessionFactory,
|
||||
OssService ossService,
|
||||
@@ -76,7 +77,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
this.importTaskService = importTaskService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
this.orderMapper = orderMapper;
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.realtimeSseService = realtimeSseService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.ossService = ossService;
|
||||
this.sysFileService = sysFileService;
|
||||
@@ -369,12 +370,34 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
private void notifyTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
if (userId == null || taskVO == null) return;
|
||||
try {
|
||||
sseNotificationService.sendTaskProgress(userId, taskVO);
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_TASK_PROGRESS,
|
||||
"task", taskVO
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_TASK_PROGRESS, payload);
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
notifyImportAllCompletedIfIdle(userId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// SSE 发送失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyImportAllCompletedIfIdle(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");
|
||||
if (importTaskService.count(wrapper) > 0) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED,
|
||||
"message", "所有任务已完成"
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED, payload);
|
||||
}
|
||||
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
if (importTaskPO == null) return null;
|
||||
ImportTaskVO vo = new ImportTaskVO();
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse;
|
||||
|
||||
/**
|
||||
* 用户级 SSE 事件名(与前端 EventSource.addEventListener 对齐)
|
||||
*/
|
||||
public final class RealtimeSseEvents {
|
||||
|
||||
private RealtimeSseEvents() {
|
||||
}
|
||||
|
||||
/** 连接建立 */
|
||||
public static final String CONNECTED = "message";
|
||||
|
||||
/** 心跳 */
|
||||
public static final String PING = "ping";
|
||||
|
||||
/** 导入任务进度 */
|
||||
public static final String IMPORT_TASK_PROGRESS = "import_task_progress";
|
||||
|
||||
/** 导入任务全部结束(可刷新列表) */
|
||||
public static final String IMPORT_ALL_TASKS_COMPLETED = "import_all_tasks_completed";
|
||||
|
||||
/** 拼多多订单全量同步任务进度 */
|
||||
public static final String PDD_ORDER_FULL_SYNC_PROGRESS = "pdd_order_full_sync_progress";
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse;
|
||||
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* 用户级实时推送(单用户多设备/多标签页)
|
||||
*/
|
||||
public interface RealtimeSseService {
|
||||
|
||||
/**
|
||||
* 建立连接
|
||||
*
|
||||
* @param userId 用户 ID
|
||||
* @param companyId 当前公司 ID(可为 null)
|
||||
* @param deviceId 设备/标签页标识
|
||||
*/
|
||||
SseEmitter createConnection(Long userId, Long companyId, String deviceId);
|
||||
|
||||
/**
|
||||
* 推送给指定用户的全部设备连接
|
||||
*/
|
||||
void sendToUser(Long userId, String eventName, Object payload);
|
||||
|
||||
/**
|
||||
* 推送给指定公司下当前在线的全部用户连接
|
||||
*/
|
||||
void sendToCompany(Long companyId, String eventName, Object payload);
|
||||
|
||||
/**
|
||||
* 关闭用户全部连接
|
||||
*/
|
||||
void closeUserConnections(Long userId);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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.modules.notify.sse.RealtimeSseService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 用户级实时通道:登录即可连接,业务事件按类型分发。
|
||||
*/
|
||||
@Tag(name = "实时通知SSE", description = "用户级实时推送(导入/同步等)")
|
||||
@RestController
|
||||
@RequestMapping("/api/notify/sse")
|
||||
public class RealtimeSseController {
|
||||
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public RealtimeSseController(RealtimeSseService realtimeSseService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.realtimeSseService = realtimeSseService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Operation(summary = "建立SSE连接", description = "登录后建立用户级 SSE;支持多设备/多标签页(deviceId)")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter connect(
|
||||
@RequestParam(value = "deviceId", required = false) String deviceId) {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
Long companyId = null;
|
||||
try {
|
||||
companyId = currentUserContext.getCurrentCompanyId();
|
||||
} catch (Exception ignored) {
|
||||
// 超管等无公司上下文时仍可连接,仅收用户级事件
|
||||
}
|
||||
return realtimeSseService.createConnection(userId, companyId, deviceId);
|
||||
}
|
||||
}
|
||||
+150
-210
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
@@ -6,103 +6,76 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* SSE通知服务实现类(多设备版本)
|
||||
*
|
||||
* 架构:Map(userId → List(EmitterWithDevice))
|
||||
* - 一个用户可有多个设备/标签页同时连接
|
||||
* - deviceId 去重:新连接同 deviceId 则关掉旧连接
|
||||
* - 单用户最大连接数:10(超出则踢最旧的)
|
||||
* 用户级 SSE:Map(userId → List(device)),同 deviceId 去重,单用户最多 10 路。
|
||||
*/
|
||||
@Service
|
||||
public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
public class RealtimeSseServiceImpl implements RealtimeSseService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(RealtimeSseServiceImpl.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 class EmitterEntry {
|
||||
final String deviceId;
|
||||
final Long companyId;
|
||||
final SseEmitter emitter;
|
||||
long lastHeartbeat;
|
||||
|
||||
EmitterEntry(String deviceId, SseEmitter emitter) {
|
||||
EmitterEntry(String deviceId, Long companyId, SseEmitter emitter) {
|
||||
this.deviceId = deviceId;
|
||||
this.companyId = companyId;
|
||||
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;
|
||||
|
||||
public SseNotificationServiceImpl(ImportTaskService importTaskService, ObjectMapper objectMapper) {
|
||||
this.importTaskService = importTaskService;
|
||||
public RealtimeSseServiceImpl(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.scheduler = new ScheduledThreadPoolExecutor(2, r -> {
|
||||
Thread t = new Thread(r, "sse-heartbeat");
|
||||
Thread t = new Thread(r, "realtime-sse-heartbeat");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 连接管理 ====================
|
||||
|
||||
/**
|
||||
* 兼容旧调用:自动生成匿名 deviceId
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId) {
|
||||
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);
|
||||
public SseEmitter createConnection(Long userId, Long companyId, String deviceId) {
|
||||
String resolvedDeviceId = (deviceId == null || deviceId.isBlank())
|
||||
? "device-" + System.nanoTime()
|
||||
: deviceId.trim();
|
||||
logger.info("创建SSE连接,userId={}, companyId={}, deviceId={}", userId, companyId, resolvedDeviceId);
|
||||
|
||||
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);
|
||||
EmitterEntry existing = findEntry(entries, resolvedDeviceId);
|
||||
if (existing != null) {
|
||||
logger.info("设备已存在连接,关闭旧连接,deviceId={}", resolvedDeviceId);
|
||||
safeComplete(existing.emitter);
|
||||
entries.remove(existing);
|
||||
}
|
||||
|
||||
// 2. 超出上限,移除最旧的连接
|
||||
if (entries.size() >= MAX_DEVICES_PER_USER) {
|
||||
EmitterEntry oldest = entries.stream()
|
||||
.min((a, b) -> Long.compare(a.lastHeartbeat, b.lastHeartbeat))
|
||||
@@ -114,37 +87,110 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 创建新 emitter
|
||||
SseEmitter emitter = new SseEmitter(SSE_TIMEOUT_MS);
|
||||
EmitterEntry newEntry = new EmitterEntry(deviceId, emitter);
|
||||
EmitterEntry newEntry = new EmitterEntry(resolvedDeviceId, companyId, emitter);
|
||||
entries.add(newEntry);
|
||||
registerCallbacks(userId, resolvedDeviceId, entries, emitter, newEntry);
|
||||
|
||||
// 4. 注册回调
|
||||
registerCallbacks(userId, deviceId, entries, emitter, newEntry);
|
||||
|
||||
// 5. 发送初始消息
|
||||
try {
|
||||
Map<String, Object> msg = Map.of(
|
||||
"type", "connected",
|
||||
"message", "SSE连接已建立",
|
||||
"deviceId", deviceId
|
||||
"deviceId", resolvedDeviceId
|
||||
);
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("message")
|
||||
.name(RealtimeSseEvents.CONNECTED)
|
||||
.data(Objects.requireNonNull(serializeForSse(msg))));
|
||||
// 建连线程立刻发一帧 ping,避免只靠调度器导致首包延迟/丢包被前端误判超时
|
||||
Map<String, Object> pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
emitter.send(SseEmitter.event()
|
||||
.name(RealtimeSseEvents.PING)
|
||||
.data(Objects.requireNonNull(serializeForSse(pingMsg))));
|
||||
newEntry.lastHeartbeat = System.currentTimeMillis();
|
||||
} catch (IOException e) {
|
||||
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, deviceId, e);
|
||||
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, resolvedDeviceId, e);
|
||||
entries.remove(newEntry);
|
||||
safeComplete(emitter);
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 6. 启动/重启心跳
|
||||
ensureHeartbeatRunning(userId);
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToUser(Long userId, String eventName, Object payload) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
logger.debug("用户没有SSE连接,userId={}", userId);
|
||||
return;
|
||||
}
|
||||
broadcast(userId, entries, eventName, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToCompany(Long companyId, String eventName, Object payload) {
|
||||
if (companyId == null) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<Long, List<EmitterEntry>> e : userConnections.entrySet()) {
|
||||
Long userId = e.getKey();
|
||||
List<EmitterEntry> companyEntries = new ArrayList<>();
|
||||
for (EmitterEntry entry : e.getValue()) {
|
||||
if (companyId.equals(entry.companyId)) {
|
||||
companyEntries.add(entry);
|
||||
}
|
||||
}
|
||||
if (!companyEntries.isEmpty()) {
|
||||
broadcast(userId, companyEntries, eventName, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeUserConnections(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);
|
||||
}
|
||||
|
||||
private void broadcast(Long userId, List<EmitterEntry> entries, String eventName, Object payload) {
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
String data;
|
||||
try {
|
||||
data = serializeForSse(payload);
|
||||
} catch (IOException ex) {
|
||||
logger.warn("SSE载荷序列化失败,userId={}, event={}", userId, eventName, ex);
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name(eventName)
|
||||
.data(Objects.requireNonNull(data)));
|
||||
} catch (IOException ex) {
|
||||
logger.debug("SSE发送失败,移除连接,userId={}, deviceId={}", userId, entry.deviceId);
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, deadEntries);
|
||||
}
|
||||
|
||||
private void registerCallbacks(Long userId, String deviceId,
|
||||
List<EmitterEntry> entries,
|
||||
SseEmitter emitter, EmitterEntry entry) {
|
||||
@@ -153,16 +199,16 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
entries.remove(entry);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
emitter.onTimeout(() -> {
|
||||
logger.info("SSE连接超时,userId={}, deviceId={}", userId, deviceId);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
emitter.onError((ex) -> {
|
||||
logger.error("SSE连接错误,userId={}, deviceId={}", userId, deviceId, ex);
|
||||
// 客户端断开时常见,避免刷 ERROR(尤其 AccessDenied + response committed)
|
||||
logger.debug("SSE连接错误,userId={}, deviceId={}, err={}",
|
||||
userId, deviceId, ex != null ? ex.getMessage() : null);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
@@ -173,68 +219,70 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) task.cancel(false);
|
||||
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;
|
||||
if (e.deviceId.equals(deviceId)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void safeComplete(SseEmitter emitter) {
|
||||
if (emitter != null) {
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception ignored) {}
|
||||
if (emitter == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
emitter.complete();
|
||||
} 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;
|
||||
|
||||
// initialDelay=0:连接建立后尽快发首帧 ping,避免客户端在「首 ping 前」用短窗口误判超时
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// 首包已在建连时发送;周期心跳从 interval 后开始
|
||||
ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(
|
||||
() -> heartbeatForUser(userId),
|
||||
0,
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
heartbeatTasks.put(userId, task);
|
||||
ScheduledFuture<?> prev = heartbeatTasks.putIfAbsent(userId, task);
|
||||
if (prev != null) {
|
||||
task.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if (t != null) {
|
||||
t.cancel(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Object> pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
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")
|
||||
.name(RealtimeSseEvents.PING)
|
||||
.data(Objects.requireNonNull(serializeForSse(pingMsg))));
|
||||
entry.lastHeartbeat = System.currentTimeMillis();
|
||||
} catch (IOException e) {
|
||||
@@ -242,63 +290,17 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, deadEntries);
|
||||
}
|
||||
|
||||
// ==================== 发送消息 ====================
|
||||
|
||||
@Override
|
||||
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
private void handleDeadEntries(Long userId, List<EmitterEntry> deadEntries) {
|
||||
if (deadEntries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
logger.debug("用户没有SSE连接,userId={}", userId);
|
||||
if (entries == null) {
|
||||
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(Objects.requireNonNull(serializeForSse(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);
|
||||
@@ -306,75 +308,13 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
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(Objects.requireNonNull(serializeForSse(msg))));
|
||||
} catch (IOException e) {
|
||||
deadEntries.add(entry);
|
||||
if (t != null) {
|
||||
t.cancel(false);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// ==================== 查询 ====================
|
||||
|
||||
/** 序列化 SSE 载荷;@NonNull 满足 IDE 对 SseEmitter.data(@NonNull Object) 的空值分析 */
|
||||
private @NonNull String serializeForSse(Object payload) throws IOException {
|
||||
return Objects.requireNonNull(objectMapper.writeValueAsString(payload));
|
||||
}
|
||||
|
||||
@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");
|
||||
return importTaskService.count(wrapper) > 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user