mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
feat: 完善任务队列真正用上redis stream
This commit is contained in:
+7
@@ -8,6 +8,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@@ -48,5 +49,11 @@ public class RedisConfig {
|
||||
template.afterPropertiesSet();
|
||||
return template;
|
||||
}
|
||||
|
||||
/** Stream 队列使用纯字符串序列化 */
|
||||
@Bean
|
||||
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
|
||||
return new StringRedisTemplate(connectionFactory);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.config;
|
||||
|
||||
/**
|
||||
* 导入任务队列配置 - Redis Streams 版本
|
||||
*/
|
||||
public class ImportTaskQueueConfig {
|
||||
|
||||
/**
|
||||
* Redis Stream 的 Key(所有导入任务类型共用一个 Stream)
|
||||
*/
|
||||
public static final String IMPORT_TASK_STREAM = "import:task:stream";
|
||||
|
||||
/**
|
||||
* 消费组名称
|
||||
*/
|
||||
public static final String IMPORT_TASK_GROUP = "import-task-group";
|
||||
|
||||
/**
|
||||
* 商品导入任务队列(保留常量,兼容旧代码)
|
||||
*/
|
||||
public static final String IMPORT_TASK_QUEUE_PRODUCT = "import:task:queue:product";
|
||||
|
||||
/**
|
||||
* 订单导入任务队列(保留常量,兼容旧代码)
|
||||
*/
|
||||
public static final String IMPORT_TASK_QUEUE_ORDER = "import:task:queue:order";
|
||||
|
||||
/**
|
||||
* 根据类型获取队列名称(保留方法,兼容旧代码)
|
||||
* 注意:Redis Streams 版本不再按类型区分队列,统一使用 STREAM_KEY
|
||||
*
|
||||
* @param type 导入类型(product/order)
|
||||
* @return 队列名称
|
||||
*/
|
||||
public static String getQueueName(String type) {
|
||||
// Redis Streams 版本统一使用 Stream
|
||||
return IMPORT_TASK_STREAM;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 导入任务 Redis Stream 队列配置。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "import-task")
|
||||
public class ImportTaskProperties {
|
||||
|
||||
private Queue queue = new Queue();
|
||||
private Worker worker = new Worker();
|
||||
|
||||
@Data
|
||||
public static class Queue {
|
||||
/** 是否启用 Redis Stream 调度 */
|
||||
private boolean enabled = true;
|
||||
private String streamPrefix = "import:task:stream";
|
||||
private String consumerGroup = "import-task-group";
|
||||
/** XREADGROUP 阻塞毫秒 */
|
||||
private long blockTimeoutMs = 5000;
|
||||
/** XAUTOCLAIM 最小空闲毫秒(PEL 回收) */
|
||||
private long claimIdleMs = 300_000;
|
||||
/** DB 对账周期毫秒 */
|
||||
private long reconcileIntervalMs = 60_000;
|
||||
/** processing 超时毫秒(心跳未更新则恢复) */
|
||||
private long stuckProcessingMs = 300_000;
|
||||
/** 对账分布式锁 TTL 秒 */
|
||||
private long reconcileLockSeconds = 55;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Worker {
|
||||
/** 各类型 worker 是否启用 */
|
||||
private Map<String, Boolean> typeEnabled = defaultTypeEnabled();
|
||||
/** 每类型并发线程数 */
|
||||
private int poolSizePerType = 1;
|
||||
|
||||
private static Map<String, Boolean> defaultTypeEnabled() {
|
||||
Map<String, Boolean> map = new LinkedHashMap<>();
|
||||
map.put("order", true);
|
||||
map.put("product", false);
|
||||
map.put("promotion_record", true);
|
||||
return map;
|
||||
}
|
||||
|
||||
public boolean isTypeEnabled(String type) {
|
||||
return typeEnabled.getOrDefault(type, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 导入任务 Redis Stream 命名。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskStreamNames {
|
||||
|
||||
public static final List<String> ALL_TYPES = List.of("order", "product", "promotion_record");
|
||||
|
||||
private final ImportTaskProperties properties;
|
||||
|
||||
public ImportTaskStreamNames(ImportTaskProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String streamKey(String type) {
|
||||
return properties.getQueue().getStreamPrefix() + ":" + type;
|
||||
}
|
||||
|
||||
public String consumerGroup() {
|
||||
return properties.getQueue().getConsumerGroup();
|
||||
}
|
||||
|
||||
public String reconcileLockKey() {
|
||||
return "import:task:reconcile:lock";
|
||||
}
|
||||
}
|
||||
+36
@@ -92,6 +92,42 @@ public class ImportTaskPO {
|
||||
@TableField("message")
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 开始处理时间
|
||||
*/
|
||||
@TableField("started_at")
|
||||
private LocalDateTime startedAt;
|
||||
|
||||
/**
|
||||
* 最后心跳时间
|
||||
*/
|
||||
@TableField("last_heartbeat_at")
|
||||
private LocalDateTime lastHeartbeatAt;
|
||||
|
||||
/**
|
||||
* 处理实例标识
|
||||
*/
|
||||
@TableField("worker_id")
|
||||
private String workerId;
|
||||
|
||||
/**
|
||||
* 入队 Stream Key
|
||||
*/
|
||||
@TableField("redis_stream_key")
|
||||
private String redisStreamKey;
|
||||
|
||||
/**
|
||||
* Redis Stream 消息 ID
|
||||
*/
|
||||
@TableField("redis_message_id")
|
||||
private String redisMessageId;
|
||||
|
||||
/**
|
||||
* 入队状态:pending_enqueue / enqueued / enqueue_failed
|
||||
*/
|
||||
@TableField("enqueue_status")
|
||||
private String enqueueStatus;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
/**
|
||||
* 生成当前 JVM 唯一的 Stream 消费者名。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskConsumerNameFactory {
|
||||
|
||||
private final String consumerName;
|
||||
|
||||
public ImportTaskConsumerNameFactory() {
|
||||
String host = "unknown";
|
||||
try {
|
||||
host = InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception ignored) {
|
||||
// 使用默认 host
|
||||
}
|
||||
long pid = ProcessHandle.current().pid();
|
||||
this.consumerName = "import-task-" + host + "-" + pid;
|
||||
}
|
||||
|
||||
public String current() {
|
||||
return consumerName;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Redis Stream 消息体(仅 taskId + type)。
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ImportTaskQueueMessage {
|
||||
|
||||
private Long taskId;
|
||||
private String type;
|
||||
|
||||
public Map<String, String> toStreamBody() {
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("taskId", String.valueOf(taskId));
|
||||
body.put("type", type);
|
||||
body.put("enqueueAt", String.valueOf(System.currentTimeMillis()));
|
||||
return body;
|
||||
}
|
||||
|
||||
public static ImportTaskQueueMessage fromStreamBody(Map<Object, Object> body) {
|
||||
if (body == null || body.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String taskIdStr = stringValue(body.get("taskId"));
|
||||
String type = stringValue(body.get("type"));
|
||||
if (taskIdStr == null || type == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new ImportTaskQueueMessage(Long.parseLong(taskIdStr), type);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String stringValue(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.domain.Range;
|
||||
import org.springframework.data.redis.connection.RedisStreamCommands;
|
||||
import org.springframework.data.redis.connection.stream.*;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Redis Stream 薄封装:入队、消费、ACK、PEL 回收。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskRedisQueue {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskRedisQueue.class);
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public ImportTaskRedisQueue(StringRedisTemplate stringRedisTemplate) {
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保消费组存在(MKSTREAM)。组已存在时静默忽略(BUSYGROUP)。
|
||||
*/
|
||||
public void ensureConsumerGroup(String streamKey, String groupName) {
|
||||
try {
|
||||
stringRedisTemplate.opsForStream().createGroup(streamKey, groupName);
|
||||
log.info("创建导入任务 Stream 消费组: stream={}, group={}", streamKey, groupName);
|
||||
} catch (DataAccessException e) {
|
||||
if (isBusyGroupException(e)) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Spring/Lettuce 常把 BUSYGROUP 包在 cause 链里,顶层 message 未必包含关键字。 */
|
||||
private boolean isBusyGroupException(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
String msg = current.getMessage();
|
||||
if (msg != null && (msg.contains("BUSYGROUP") || msg.contains("already exists"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 入队并返回 messageId。
|
||||
*/
|
||||
public String enqueue(String streamKey, ImportTaskQueueMessage message) {
|
||||
MapRecord<String, String, String> record = StreamRecords.string(message.toStreamBody())
|
||||
.withStreamKey(streamKey);
|
||||
RecordId recordId = stringRedisTemplate.opsForStream().add(record);
|
||||
return recordId.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 阻塞读取新消息(>)。
|
||||
*/
|
||||
public List<ImportTaskStreamRecord> readNew(String streamKey, String groupName, String consumerName, long blockMs) {
|
||||
List<MapRecord<String, Object, Object>> records = stringRedisTemplate.opsForStream().read(
|
||||
Consumer.from(groupName, consumerName),
|
||||
StreamReadOptions.empty().count(10).block(Duration.ofMillis(Math.max(1, blockMs))),
|
||||
StreamOffset.create(streamKey, ReadOffset.lastConsumed()));
|
||||
return toRecords(streamKey, records);
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收超时 PEL 消息:先 XPENDING 再 XCLAIM(当前 Spring Data Redis 无 XAUTOCLAIM 封装)。
|
||||
*/
|
||||
public List<ImportTaskStreamRecord> autoClaim(String streamKey, String groupName, String consumerName, long minIdleMs) {
|
||||
try {
|
||||
Duration minIdle = Duration.ofMillis(Math.max(1, minIdleMs));
|
||||
PendingMessages pending = stringRedisTemplate.opsForStream()
|
||||
.pending(streamKey, groupName, Range.unbounded(), 10);
|
||||
if (pending == null || pending.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
String[] staleIds = pending.stream()
|
||||
.filter(pm -> !pm.getElapsedTimeSinceLastDelivery().minus(minIdle).isNegative())
|
||||
.map(PendingMessage::getIdAsString)
|
||||
.toArray(String[]::new);
|
||||
if (staleIds.length == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<MapRecord<String, Object, Object>> claimed = stringRedisTemplate.opsForStream().claim(
|
||||
streamKey,
|
||||
groupName,
|
||||
consumerName,
|
||||
RedisStreamCommands.XClaimOptions.minIdle(minIdle).ids(staleIds));
|
||||
return toRecords(streamKey, claimed);
|
||||
} catch (Exception e) {
|
||||
log.warn("XCLAIM 回收 PEL 失败 stream={}: {}", streamKey, e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
public void ack(String streamKey, String groupName, String messageId) {
|
||||
stringRedisTemplate.opsForStream().acknowledge(streamKey, groupName, messageId);
|
||||
}
|
||||
|
||||
public long streamLength(String streamKey) {
|
||||
Long len = stringRedisTemplate.opsForStream().size(streamKey);
|
||||
return len == null ? 0 : len;
|
||||
}
|
||||
|
||||
private List<ImportTaskStreamRecord> toRecords(String streamKey, List<MapRecord<String, Object, Object>> records) {
|
||||
if (records == null || records.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<ImportTaskStreamRecord> result = new ArrayList<>();
|
||||
for (MapRecord<String, Object, Object> record : records) {
|
||||
ImportTaskQueueMessage message = ImportTaskQueueMessage.fromStreamBody(record.getValue());
|
||||
if (message == null) {
|
||||
log.warn("忽略无效 Stream 消息: stream={}, id={}", streamKey, record.getId());
|
||||
continue;
|
||||
}
|
||||
result.add(new ImportTaskStreamRecord(streamKey, record.getId().getValue(), message));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 从 Redis Stream 读取到的一条记录。
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ImportTaskStreamRecord {
|
||||
|
||||
private String streamKey;
|
||||
private String messageId;
|
||||
private ImportTaskQueueMessage message;
|
||||
}
|
||||
+29
-19
@@ -8,34 +8,44 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.dto.ImportTaskFil
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.vo.ImportTaskVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 导入任务服务接口
|
||||
*/
|
||||
public interface ImportTaskService extends IService<ImportTaskPO> {
|
||||
|
||||
/**
|
||||
* 创建导入任务
|
||||
*
|
||||
* @param createImportTaskDTO 创建导入任务DTO
|
||||
* @return 导入任务VO
|
||||
*/
|
||||
ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO);
|
||||
|
||||
/**
|
||||
* 分页获取导入任务列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<ImportTaskVO> getImportTaskPage(PageQueryDTO<ImportTaskFilterDTO> pageQueryDTO);
|
||||
|
||||
/**
|
||||
* 获取并锁定一个待处理的导入任务
|
||||
* 使用 FOR UPDATE SKIP LOCKED 防止多消费者重复获取同一任务
|
||||
*
|
||||
* @param type 任务类型 (order/product)
|
||||
* @return 被锁定的任务PO,如果没有任何待处理任务则返回null
|
||||
* 消费端抢锁:仅 pending 可转为 processing(幂等)。
|
||||
*/
|
||||
ImportTaskPO fetchAndLockPendingTask(String type);
|
||||
}
|
||||
ImportTaskPO tryClaimForProcessing(Long taskId, String workerId);
|
||||
|
||||
/**
|
||||
* 标记任务失败
|
||||
*/
|
||||
void markFailed(Long taskId, String message);
|
||||
|
||||
/**
|
||||
* 刷新长任务心跳
|
||||
*/
|
||||
void touchHeartbeat(Long taskId);
|
||||
|
||||
/**
|
||||
* 查询需要补入队的 pending 任务
|
||||
*/
|
||||
List<ImportTaskPO> listPendingEnqueueTasks();
|
||||
|
||||
/**
|
||||
* 查询 processing 超时任务
|
||||
*/
|
||||
List<ImportTaskPO> listStuckProcessingTasks(long stuckThresholdMs);
|
||||
|
||||
/**
|
||||
* 重置为 pending 并等待对账入队
|
||||
*/
|
||||
void resetToPendingForRecovery(Long taskId, String message);
|
||||
}
|
||||
|
||||
+157
-117
@@ -3,59 +3,77 @@ package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskConsumerNameFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskStreamRecord;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskConsumerService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.worker.ImportTaskRecoveryService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 导入任务消费者服务 - 数据库轮询方案
|
||||
*
|
||||
* 工作原理:
|
||||
* 1. 定时轮询数据库,查找 status='pending' 的任务(按创建时间顺序)
|
||||
* 2. 使用 FOR UPDATE SKIP LOCKED 防止多消费者重复获取同一任务
|
||||
* 3. 获取到任务后立即将状态改为 'processing'(悲观锁保护)
|
||||
* 4. 处理任务,处理完成后更新状态为 'success' 或 'failed'
|
||||
* 5. 服务重启后,'processing' 状态超过 10 分钟的任务自动重置为 'pending'
|
||||
*
|
||||
* 优点:
|
||||
* - 简单可靠,不依赖复杂的 Redis Streams API
|
||||
* - 数据持久化,服务挂掉可恢复
|
||||
* - 不需要额外的消息队列中间件
|
||||
* 导入任务消费者:Redis Stream + DB 状态机。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskConsumerServiceImpl.class);
|
||||
private static final long POLL_INTERVAL_MS = 3000; // 3秒轮询一次
|
||||
private static final long STUCK_THRESHOLD_MS = 10 * 60 * 1000; // 10分钟
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskConsumerServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskProcessorService importTaskProcessorService;
|
||||
private final ExecutorService executorService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
private final ImportTaskConsumerNameFactory consumerNameFactory;
|
||||
private final ImportTaskRecoveryService recoveryService;
|
||||
|
||||
private ExecutorService executorService;
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
private final String consumerName;
|
||||
|
||||
public ImportTaskConsumerServiceImpl(ImportTaskService importTaskService,
|
||||
ImportTaskProcessorService importTaskProcessorService) {
|
||||
ImportTaskProcessorService importTaskProcessorService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties,
|
||||
ImportTaskConsumerNameFactory consumerNameFactory,
|
||||
ImportTaskRecoveryService recoveryService) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.importTaskProcessorService = importTaskProcessorService;
|
||||
this.executorService = Executors.newFixedThreadPool(3);
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
this.consumerNameFactory = consumerNameFactory;
|
||||
this.recoveryService = recoveryService;
|
||||
this.consumerName = consumerNameFactory.current();
|
||||
}
|
||||
|
||||
@jakarta.annotation.PostConstruct
|
||||
public void init() {
|
||||
logger.info("初始化导入任务消费者...");
|
||||
// 启动时先恢复卡住的任务
|
||||
recoverStuckTasks();
|
||||
// 启动消费者
|
||||
/**
|
||||
* 等 Web 容器就绪后再启动消费者,避免端口占用等启动失败时 Redis 长阻塞连接被强制断开。
|
||||
*/
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationReady() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.warn("导入任务 Redis 队列未启用,消费者不启动");
|
||||
return;
|
||||
}
|
||||
log.info("初始化导入任务 Redis Stream 消费者,consumer={}", consumerName);
|
||||
recoveryService.recoverOnStartup();
|
||||
startConsumers();
|
||||
logger.info("导入任务消费者初始化完成");
|
||||
log.info("导入任务消费者初始化完成");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@@ -65,117 +83,139 @@ public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService
|
||||
|
||||
@Override
|
||||
public void startConsumers() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (running.compareAndSet(false, true)) {
|
||||
logger.info("启动导入任务消费者...");
|
||||
// 启动三个消费者线程(订单、商品、推广费)
|
||||
executorService.submit(() -> consumeLoop("order"));
|
||||
executorService.submit(() -> consumeLoop("product"));
|
||||
executorService.submit(() -> consumeLoop("promotion_record"));
|
||||
logger.info("导入任务消费者已启动");
|
||||
int totalThreads = 0;
|
||||
List<Runnable> tasks = new ArrayList<>();
|
||||
for (String type : ImportTaskStreamNames.ALL_TYPES) {
|
||||
if (!properties.getWorker().isTypeEnabled(type)) {
|
||||
log.info("导入任务类型 {} 的 worker 已禁用", type);
|
||||
continue;
|
||||
}
|
||||
String streamKey = streamNames.streamKey(type);
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
int pool = Math.max(1, properties.getWorker().getPoolSizePerType());
|
||||
for (int i = 0; i < pool; i++) {
|
||||
String threadConsumer = consumerName + "-" + type + "-" + i;
|
||||
tasks.add(() -> consumeLoop(streamKey, type, threadConsumer));
|
||||
totalThreads++;
|
||||
}
|
||||
}
|
||||
executorService = Executors.newFixedThreadPool(Math.max(1, totalThreads));
|
||||
for (Runnable task : tasks) {
|
||||
executorService.submit(task);
|
||||
}
|
||||
log.info("导入任务 Redis Stream 消费者已启动,threads={}", totalThreads);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopConsumers() {
|
||||
if (running.compareAndSet(true, false)) {
|
||||
logger.info("停止导入任务消费者...");
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
logger.info("导入任务消费者已停止");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复卡住的任务(processing 状态超过 10 分钟的)
|
||||
*/
|
||||
private void recoverStuckTasks() {
|
||||
try {
|
||||
logger.info("检查并恢复卡住的 processing 任务...");
|
||||
long threshold = System.currentTimeMillis() - STUCK_THRESHOLD_MS;
|
||||
java.sql.Timestamp thresholdTime = new java.sql.Timestamp(threshold);
|
||||
|
||||
// 查找 processing 状态且更新时间超过阈值的任务
|
||||
var wrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO>()
|
||||
.eq(ImportTaskPO::getStatus, "processing")
|
||||
.lt(ImportTaskPO::getUpdateTime, thresholdTime);
|
||||
|
||||
var stuckTasks = importTaskService.list(wrapper);
|
||||
if (stuckTasks != null && !stuckTasks.isEmpty()) {
|
||||
logger.info("发现 {} 个卡住的 processing 任务,尝试恢复...", stuckTasks.size());
|
||||
for (ImportTaskPO task : stuckTasks) {
|
||||
try {
|
||||
task.setStatus("pending");
|
||||
task.setMessage("服务重启,自动恢复");
|
||||
importTaskService.updateById(task);
|
||||
logger.info("任务 {} 已恢复为 pending", task.getId());
|
||||
} catch (Exception e) {
|
||||
logger.error("恢复任务 {} 失败: {}", task.getId(), e.getMessage());
|
||||
log.info("停止导入任务消费者...");
|
||||
if (executorService != null) {
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(30, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
} else {
|
||||
logger.info("没有发现卡住的任务");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("恢复卡住任务时发生异常", e);
|
||||
log.info("导入任务消费者已停止");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费循环
|
||||
* @param type 任务类型 (order/product)
|
||||
*/
|
||||
private void consumeLoop(String type) {
|
||||
logger.info("开始消费{}导入任务", type);
|
||||
|
||||
private void consumeLoop(String streamKey, String type, String threadConsumer) {
|
||||
log.info("开始消费 {} 导入任务,stream={}, consumer={}", type, streamKey, threadConsumer);
|
||||
long blockMs = properties.getQueue().getBlockTimeoutMs();
|
||||
long claimIdleMs = properties.getQueue().getClaimIdleMs();
|
||||
String group = streamNames.consumerGroup();
|
||||
|
||||
while (running.get()) {
|
||||
try {
|
||||
// 查找并锁定一个 pending 任务
|
||||
ImportTaskPO task = importTaskService.fetchAndLockPendingTask(type);
|
||||
|
||||
if (task != null) {
|
||||
logger.info("获取到{}导入任务,taskId: {}, taskName: {}", type, task.getId(), task.getTaskName());
|
||||
|
||||
try {
|
||||
// 处理任务
|
||||
importTaskProcessorService.processImportTask(task.getId());
|
||||
logger.info("任务 {} 处理成功", task.getId());
|
||||
} catch (Exception e) {
|
||||
logger.error("任务 {} 处理失败: {}", task.getId(), e.getMessage(), e);
|
||||
// 处理失败,更新任务状态
|
||||
try {
|
||||
task.setStatus("failed");
|
||||
task.setMessage("处理失败: " + e.getMessage());
|
||||
importTaskService.updateById(task);
|
||||
} catch (Exception updateEx) {
|
||||
logger.error("更新任务 {} 状态失败: {}", task.getId(), updateEx.getMessage());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有待处理的任务,休眠一段时间
|
||||
Thread.sleep(POLL_INTERVAL_MS);
|
||||
List<ImportTaskStreamRecord> records = redisQueue.autoClaim(streamKey, group, threadConsumer, claimIdleMs);
|
||||
if (records.isEmpty()) {
|
||||
records = redisQueue.readNew(streamKey, group, threadConsumer, blockMs);
|
||||
}
|
||||
if (records.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
for (ImportTaskStreamRecord record : records) {
|
||||
handleRecord(streamKey, group, record);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.info("{}消费者线程被中断,退出", type);
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
logger.error("消费{}任务时发生异常: {}", type, e.getClass().getName(), e);
|
||||
try {
|
||||
Thread.sleep(5000); // 出错时多等一会儿
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
if (!running.get()) {
|
||||
break;
|
||||
}
|
||||
// 应用关闭或连接池回收时常见,降级日志避免误报
|
||||
if (isRedisConnectionIssue(e)) {
|
||||
log.warn("消费 {} Redis 连接中断,3s 后重试: {}", type, rootCauseMessage(e));
|
||||
} else {
|
||||
log.error("消费 {} 任务异常: {}", type, e.getMessage(), e);
|
||||
}
|
||||
sleepQuietly(3000);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("{}导入任务消费者已停止", type);
|
||||
log.info("{} 导入任务消费者已停止,consumer={}", type, threadConsumer);
|
||||
}
|
||||
|
||||
private void handleRecord(String streamKey, String group, ImportTaskStreamRecord record) {
|
||||
Long taskId = record.getMessage().getTaskId();
|
||||
try {
|
||||
ImportTaskPO claimed = importTaskService.tryClaimForProcessing(taskId, consumerName);
|
||||
if (claimed == null) {
|
||||
log.info("任务 {} 已被其他实例处理或状态非 pending,直接 ACK", taskId);
|
||||
redisQueue.ack(streamKey, group, record.getMessageId());
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("开始处理导入任务 taskId={}, type={}", taskId, claimed.getType());
|
||||
importTaskProcessorService.processImportTask(taskId);
|
||||
log.info("导入任务处理完成 taskId={}", taskId);
|
||||
} catch (Exception e) {
|
||||
log.error("导入任务 {} 处理失败: {}", taskId, e.getMessage(), e);
|
||||
importTaskService.markFailed(taskId, "处理失败: " + e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
redisQueue.ack(streamKey, group, record.getMessageId());
|
||||
} catch (Exception ackEx) {
|
||||
log.warn("ACK 任务 {} 失败: {}", taskId, ackEx.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isRedisConnectionIssue(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
String msg = current.getMessage();
|
||||
if (msg != null && (msg.contains("Connection closed")
|
||||
|| msg.contains("Connection reset")
|
||||
|| msg.contains("Redis exception"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String rootCauseMessage(Throwable throwable) {
|
||||
Throwable root = throwable;
|
||||
while (root.getCause() != null) {
|
||||
root = root.getCause();
|
||||
}
|
||||
return root.getMessage() == null ? throwable.getMessage() : root.getMessage();
|
||||
}
|
||||
|
||||
private void sleepQuietly(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -415,6 +415,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
if (totalCount != null) updateWrapper.set(ImportTaskPO::getTotalCount, totalCount);
|
||||
if (successCount != null) updateWrapper.set(ImportTaskPO::getSuccessCount, successCount);
|
||||
if (failCount != null) updateWrapper.set(ImportTaskPO::getFailCount, failCount);
|
||||
if ("processing".equals(status)) {
|
||||
updateWrapper.set(ImportTaskPO::getLastHeartbeatAt, java.time.LocalDateTime.now());
|
||||
}
|
||||
importTaskService.update(updateWrapper);
|
||||
}
|
||||
|
||||
|
||||
+45
-23
@@ -4,54 +4,76 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskQueueMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
|
||||
|
||||
/**
|
||||
* 导入任务队列服务 - 数据库轮询方案
|
||||
*
|
||||
* 由于消费者通过轮询数据库获取任务,生产者只需确保任务状态为 'pending' 即可。
|
||||
* 不需要向任何消息队列发布消息。
|
||||
* 导入任务 Redis Stream 生产者。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskQueueServiceImpl implements ImportTaskQueueService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskQueueServiceImpl.class);
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskQueueServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
|
||||
public ImportTaskQueueServiceImpl(@Lazy ImportTaskService importTaskService) {
|
||||
public ImportTaskQueueServiceImpl(@Lazy ImportTaskService importTaskService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布导入任务
|
||||
* 数据库轮询方案:只需确保任务已创建(status=pending),消费者会轮询发现
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
@Override
|
||||
public void publishImportTask(Long taskId) {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.warn("导入任务 Redis 队列未启用,taskId={} 仅保留 DB pending 状态", taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
logger.error("导入任务不存在,taskId: {}", taskId);
|
||||
log.error("导入任务不存在,taskId={}", taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保任务状态是 pending
|
||||
if (!"pending".equals(task.getStatus())) {
|
||||
task.setStatus("pending");
|
||||
importTaskService.updateById(task);
|
||||
log.info("任务 {} 非 pending,跳过入队,status={}", taskId, task.getStatus());
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("导入任务已就绪,taskId: {}, type: {}, status: {}",
|
||||
taskId, task.getType(), task.getStatus());
|
||||
// 消费者通过轮询数据库会发现这个任务,无需额外通知
|
||||
|
||||
|
||||
String streamKey = streamNames.streamKey(task.getType());
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
|
||||
String messageId = redisQueue.enqueue(streamKey, new ImportTaskQueueMessage(taskId, task.getType()));
|
||||
|
||||
ImportTaskPO update = new ImportTaskPO();
|
||||
update.setId(taskId);
|
||||
update.setEnqueueStatus("enqueued");
|
||||
update.setRedisStreamKey(streamKey);
|
||||
update.setRedisMessageId(messageId);
|
||||
importTaskService.updateById(update);
|
||||
|
||||
log.info("导入任务已入队 Redis Stream,taskId={}, type={}, stream={}, messageId={}",
|
||||
taskId, task.getType(), streamKey, messageId);
|
||||
} catch (Exception e) {
|
||||
logger.error("发布导入任务失败,taskId: {}", taskId, e);
|
||||
log.error("导入任务入队失败,taskId={}", taskId, e);
|
||||
ImportTaskPO update = new ImportTaskPO();
|
||||
update.setId(taskId);
|
||||
update.setEnqueueStatus("enqueue_failed");
|
||||
update.setMessage("入队失败: " + e.getMessage());
|
||||
importTaskService.updateById(update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+90
-69
@@ -1,7 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -11,6 +11,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.mapper.ImportTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.dto.CreateImportTaskDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.dto.ImportTaskFilterDTO;
|
||||
@@ -18,13 +19,15 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeature;
|
||||
import top.xyquan.ecomdmbbackend.modules.license.LicenseFeatureGuard;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -36,45 +39,35 @@ import java.util.stream.Collectors;
|
||||
public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportTaskPO> implements ImportTaskService {
|
||||
|
||||
private final ShopService shopService;
|
||||
|
||||
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ImportTaskQueueService importTaskQueueService;
|
||||
private final LicenseFeatureGuard licenseFeatureGuard;
|
||||
|
||||
public ImportTaskServiceImpl(CurrentUserContext currentUserContext,
|
||||
ImportTaskQueueService importTaskQueueService,
|
||||
ShopService shopService,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
ImportTaskQueueService importTaskQueueService,
|
||||
ShopService shopService,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.importTaskQueueService = importTaskQueueService;
|
||||
this.shopService = shopService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建导入任务
|
||||
*
|
||||
* @param createImportTaskDTO 创建导入任务DTO
|
||||
* @return 导入任务VO
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO) {
|
||||
if ("order".equals(createImportTaskDTO.getType())) {
|
||||
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
|
||||
}
|
||||
// 从token中获取公司ID
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long currentUserId = currentUserContext.getCurrentUserId();
|
||||
|
||||
// 创建导入任务
|
||||
ImportTaskPO importTaskPO = new ImportTaskPO();
|
||||
BeanCopyUtils.copyProperties(createImportTaskDTO, importTaskPO);
|
||||
importTaskPO.setCompanyId(companyId);
|
||||
importTaskPO.setTaskName(generateTaskName(companyId, createImportTaskDTO.getType()));
|
||||
importTaskPO.setStatus("pending"); // 初始状态为待处理
|
||||
importTaskPO.setStatus("pending");
|
||||
importTaskPO.setEnqueueStatus("pending_enqueue");
|
||||
importTaskPO.setTotalCount(0);
|
||||
importTaskPO.setSuccessCount(0);
|
||||
importTaskPO.setFailCount(0);
|
||||
@@ -82,7 +75,6 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
|
||||
this.save(importTaskPO);
|
||||
|
||||
// 在事务提交后再发布任务到Redis队列,确保数据已提交到数据库
|
||||
Long taskId = importTaskPO.getId();
|
||||
TransactionSynchronizationManager.registerSynchronization(
|
||||
new org.springframework.transaction.support.TransactionSynchronization() {
|
||||
@@ -93,22 +85,14 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
}
|
||||
);
|
||||
|
||||
// 转换为VO返回
|
||||
return convertToVO(importTaskPO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取导入任务列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果VO
|
||||
*/
|
||||
@Override
|
||||
public PageResultVO<ImportTaskVO> getImportTaskPage(PageQueryDTO<ImportTaskFilterDTO> pageQueryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ImportTaskFilterDTO filter = pageQueryDTO.getFilters();
|
||||
|
||||
// 构建查询条件
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCompanyId, companyId);
|
||||
|
||||
@@ -127,14 +111,11 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
}
|
||||
}
|
||||
|
||||
// 按创建时间倒序
|
||||
wrapper.orderByDesc(ImportTaskPO::getCreateTime);
|
||||
|
||||
// 分页查询
|
||||
Page<ImportTaskPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
IPage<ImportTaskPO> pageResult = this.page(page, wrapper);
|
||||
|
||||
// 转换为VO
|
||||
List<ImportTaskVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
@@ -142,9 +123,76 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为VO
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ImportTaskPO tryClaimForProcessing(Long taskId, String workerId) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "pending")
|
||||
.set(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getWorkerId, workerId)
|
||||
.set(ImportTaskPO::getStartedAt, LocalDateTime.now())
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
|
||||
if (!this.update(updateWrapper)) {
|
||||
return null;
|
||||
}
|
||||
return this.getById(taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markFailed(Long taskId, String message) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.set(ImportTaskPO::getStatus, "failed")
|
||||
.set(ImportTaskPO::getMessage, message)
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touchHeartbeat(Long taskId) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ImportTaskPO> listPendingEnqueueTasks() {
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getStatus, "pending")
|
||||
.in(ImportTaskPO::getEnqueueStatus, "pending_enqueue", "enqueue_failed")
|
||||
.orderByAsc(ImportTaskPO::getId);
|
||||
return this.list(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ImportTaskPO> listStuckProcessingTasks(long stuckThresholdMs) {
|
||||
LocalDateTime threshold = LocalDateTime.now().minus(Duration.ofMillis(stuckThresholdMs));
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getStatus, "processing")
|
||||
.and(w -> w.isNull(ImportTaskPO::getLastHeartbeatAt)
|
||||
.or()
|
||||
.lt(ImportTaskPO::getLastHeartbeatAt, threshold))
|
||||
.orderByAsc(ImportTaskPO::getId);
|
||||
return this.list(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetToPendingForRecovery(Long taskId, String message) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getStatus, "pending")
|
||||
.set(ImportTaskPO::getEnqueueStatus, "pending_enqueue")
|
||||
.set(ImportTaskPO::getWorkerId, null)
|
||||
.set(ImportTaskPO::getStartedAt, null)
|
||||
.set(ImportTaskPO::getMessage, message);
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
ImportTaskVO importTaskVO = new ImportTaskVO();
|
||||
BeanCopyUtils.copyProperties(importTaskPO, importTaskVO);
|
||||
@@ -157,24 +205,21 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
return importTaskVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成唯一的任务名称
|
||||
* 格式: {type前缀}-{companyId}-{日期}-{当日序号}
|
||||
* 例如: ORDER-1-20260329-001
|
||||
* 保证同一公司内不会重名
|
||||
*/
|
||||
private String generateTaskName(Long companyId, String type) {
|
||||
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
|
||||
String typePrefix = "ORDER".equals(type) ? "ORD" : "PROD";
|
||||
|
||||
// 查询该公司当天最大的任务序号
|
||||
String typePrefix = switch (type) {
|
||||
case "order" -> "ORD";
|
||||
case "promotion_record" -> "PRM";
|
||||
default -> "PROD";
|
||||
};
|
||||
|
||||
String prefixPattern = typePrefix + "-" + companyId + "-" + dateStr + "-%";
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.likeRight(ImportTaskPO::getTaskName, prefixPattern);
|
||||
wrapper.orderByDesc(ImportTaskPO::getTaskName);
|
||||
wrapper.last("LIMIT 1");
|
||||
ImportTaskPO lastTask = this.getOne(wrapper);
|
||||
|
||||
|
||||
int seq = 1;
|
||||
if (lastTask != null && lastTask.getTaskName() != null) {
|
||||
String lastName = lastTask.getTaskName();
|
||||
@@ -183,36 +228,12 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
String lastSeqStr = lastName.substring(lastDashIndex + 1);
|
||||
try {
|
||||
seq = Integer.parseInt(lastSeqStr) + 1;
|
||||
} catch (NumberFormatException e) {
|
||||
} catch (NumberFormatException ignored) {
|
||||
seq = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return String.format("%s-%d-%s-%03d", typePrefix, companyId, dateStr, seq);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ImportTaskPO fetchAndLockPendingTask(String type) {
|
||||
// 乐观锁方式:先查后改
|
||||
// 查找一条 pending 状态的任务
|
||||
LambdaQueryWrapper<ImportTaskPO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(ImportTaskPO::getStatus, "pending")
|
||||
.eq(ImportTaskPO::getType, type)
|
||||
.orderByAsc(ImportTaskPO::getId)
|
||||
.last("LIMIT 1 FOR UPDATE SKIP LOCKED");
|
||||
|
||||
ImportTaskPO task = this.getOne(queryWrapper);
|
||||
|
||||
if (task != null) {
|
||||
// 更新为 processing
|
||||
task.setStatus("processing");
|
||||
this.updateById(task);
|
||||
return task;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.worker;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 启动恢复 + 定时对账:DB 真相源补入 Redis Stream。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskRecoveryService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskRecoveryService.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskQueueService importTaskQueueService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public ImportTaskRecoveryService(ImportTaskService importTaskService,
|
||||
ImportTaskQueueService importTaskQueueService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties,
|
||||
StringRedisTemplate stringRedisTemplate) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.importTaskQueueService = importTaskQueueService;
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动时执行一次全量对账。
|
||||
*/
|
||||
public void recoverOnStartup() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.info("导入任务 Redis 队列未启用,跳过启动对账");
|
||||
return;
|
||||
}
|
||||
log.info("导入任务启动对账开始...");
|
||||
for (String type : ImportTaskStreamNames.ALL_TYPES) {
|
||||
String streamKey = streamNames.streamKey(type);
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
}
|
||||
reconcileInternal();
|
||||
log.info("导入任务启动对账完成");
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${import-task.queue.reconcile-interval-ms:60000}")
|
||||
public void scheduledReconcile() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!tryAcquireReconcileLock()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
reconcileInternal();
|
||||
} finally {
|
||||
releaseReconcileLock();
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileInternal() {
|
||||
recoverStuckProcessingTasks();
|
||||
reenqueuePendingTasks();
|
||||
}
|
||||
|
||||
private void recoverStuckProcessingTasks() {
|
||||
long stuckMs = properties.getQueue().getStuckProcessingMs();
|
||||
List<ImportTaskPO> stuckTasks = importTaskService.listStuckProcessingTasks(stuckMs);
|
||||
if (stuckTasks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
log.warn("发现 {} 个 processing 超时任务,重置为 pending", stuckTasks.size());
|
||||
for (ImportTaskPO task : stuckTasks) {
|
||||
importTaskService.resetToPendingForRecovery(task.getId(), "处理超时,自动恢复");
|
||||
importTaskQueueService.publishImportTask(task.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void reenqueuePendingTasks() {
|
||||
List<ImportTaskPO> pendingTasks = importTaskService.listPendingEnqueueTasks();
|
||||
if (pendingTasks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
log.info("对账补入队 {} 个 pending 任务", pendingTasks.size());
|
||||
for (ImportTaskPO task : pendingTasks) {
|
||||
importTaskQueueService.publishImportTask(task.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryAcquireReconcileLock() {
|
||||
Boolean ok = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
streamNames.reconcileLockKey(),
|
||||
"1",
|
||||
Duration.ofSeconds(properties.getQueue().getReconcileLockSeconds()));
|
||||
return Boolean.TRUE.equals(ok);
|
||||
}
|
||||
|
||||
private void releaseReconcileLock() {
|
||||
stringRedisTemplate.delete(streamNames.reconcileLockKey());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user