mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 完善任务队列真正用上redis stream
This commit is contained in:
@@ -98,6 +98,12 @@ CREATE TABLE `ec_import_tasks` (
|
||||
`fail_count` int UNSIGNED NULL DEFAULT 0 COMMENT '失败行数',
|
||||
`mapping` json NULL COMMENT '字段映射记录',
|
||||
`message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '错误信息或备注',
|
||||
`started_at` datetime NULL DEFAULT NULL COMMENT '开始处理时间',
|
||||
`last_heartbeat_at` datetime NULL DEFAULT NULL COMMENT '最后心跳时间',
|
||||
`worker_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '处理实例标识',
|
||||
`redis_stream_key` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '入队 Stream Key',
|
||||
`redis_message_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'Redis Stream 消息ID',
|
||||
`enqueue_status` enum('pending_enqueue','enqueued','enqueue_failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending_enqueue' COMMENT '入队状态',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
@@ -107,6 +113,9 @@ CREATE TABLE `ec_import_tasks` (
|
||||
INDEX `idx_create_by`(`create_by` ASC) USING BTREE,
|
||||
INDEX `idx_update_by`(`update_by` ASC) USING BTREE,
|
||||
INDEX `idx_file_id`(`file_id` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_dispatch`(`status` ASC, `type` ASC, `id` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_recover`(`status` ASC, `last_heartbeat_at` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_enqueue`(`enqueue_status` ASC, `status` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_import_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_import_task_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_import_task_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
-- 导入任务 Redis Stream 队列:调度元数据 + 轮询索引
|
||||
ALTER TABLE ec_import_tasks
|
||||
ADD COLUMN started_at DATETIME NULL COMMENT '开始处理时间' AFTER message,
|
||||
ADD COLUMN last_heartbeat_at DATETIME NULL COMMENT '最后心跳时间' AFTER started_at,
|
||||
ADD COLUMN worker_id VARCHAR(128) NULL COMMENT '处理实例标识' AFTER last_heartbeat_at,
|
||||
ADD COLUMN redis_stream_key VARCHAR(128) NULL COMMENT '入队 Stream Key' AFTER worker_id,
|
||||
ADD COLUMN redis_message_id VARCHAR(64) NULL COMMENT 'Redis Stream 消息ID' AFTER redis_stream_key,
|
||||
ADD COLUMN enqueue_status ENUM('pending_enqueue', 'enqueued', 'enqueue_failed')
|
||||
NOT NULL DEFAULT 'pending_enqueue' COMMENT '入队状态' AFTER redis_message_id;
|
||||
|
||||
CREATE INDEX idx_import_task_dispatch ON ec_import_tasks (status, type, id);
|
||||
CREATE INDEX idx_import_task_recover ON ec_import_tasks (status, last_heartbeat_at);
|
||||
CREATE INDEX idx_import_task_enqueue ON ec_import_tasks (enqueue_status, status);
|
||||
|
||||
-- 历史数据:已结束任务视为已入队;待处理任务等待启动对账重入队
|
||||
UPDATE ec_import_tasks SET enqueue_status = 'enqueued'
|
||||
WHERE status IN ('success', 'failed', 'processing');
|
||||
|
||||
UPDATE ec_import_tasks SET enqueue_status = 'pending_enqueue'
|
||||
WHERE status = 'pending';
|
||||
+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());
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,24 @@ order-stat:
|
||||
ttl-today-seconds: 900
|
||||
nightly-rebuild-cron: "0 30 2 * * ?"
|
||||
|
||||
# 导入任务 Redis Stream 队列(DB 为真相源,Redis 负责调度)
|
||||
import-task:
|
||||
queue:
|
||||
enabled: true
|
||||
stream-prefix: import:task:stream
|
||||
consumer-group: import-task-group
|
||||
block-timeout-ms: 5000
|
||||
claim-idle-ms: 300000
|
||||
reconcile-interval-ms: 60000
|
||||
stuck-processing-ms: 300000
|
||||
reconcile-lock-seconds: 55
|
||||
worker:
|
||||
pool-size-per-type: 1
|
||||
type-enabled:
|
||||
order: true
|
||||
product: false
|
||||
promotion_record: true
|
||||
|
||||
# JWT 令牌有效期(密钥见各环境配置)
|
||||
jwt:
|
||||
access-token-expiration: 900
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
-- 操作日志表
|
||||
CREATE TABLE IF NOT EXISTS `sys_oper_log` (
|
||||
`id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
|
||||
`company_id` BIGINT DEFAULT NULL COMMENT '公司ID',
|
||||
`user_id` BIGINT DEFAULT NULL COMMENT '用户ID',
|
||||
`username` VARCHAR(100) DEFAULT NULL COMMENT '用户名',
|
||||
`module` VARCHAR(100) DEFAULT NULL COMMENT '模块名称',
|
||||
`oper_type` VARCHAR(20) DEFAULT NULL COMMENT '操作类型',
|
||||
`description` VARCHAR(500) DEFAULT NULL COMMENT '操作描述',
|
||||
`method` VARCHAR(500) DEFAULT NULL COMMENT '请求方法',
|
||||
`url` VARCHAR(500) DEFAULT NULL COMMENT '请求路径',
|
||||
`params` TEXT COMMENT '请求参数',
|
||||
`duration` BIGINT DEFAULT NULL COMMENT '执行时长(ms)',
|
||||
`ip` VARCHAR(50) DEFAULT NULL COMMENT 'IP地址',
|
||||
`result` VARCHAR(20) DEFAULT NULL COMMENT '操作结果(success/fail)',
|
||||
`error_msg` VARCHAR(1000) DEFAULT NULL COMMENT '错误信息',
|
||||
`operate_time` DATETIME DEFAULT NULL COMMENT '操作时间',
|
||||
INDEX `idx_company_id` (`company_id`),
|
||||
INDEX `idx_user_id` (`user_id`),
|
||||
INDEX `idx_operate_time` (`operate_time`),
|
||||
INDEX `idx_module` (`module`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';
|
||||
@@ -1,2 +0,0 @@
|
||||
-- 文件存储类型: LOCAL-本地存储, OSS-阿里云OSS
|
||||
ALTER TABLE `sys_file` ADD COLUMN `storage_type` VARCHAR(20) NOT NULL DEFAULT 'OSS' COMMENT '存储类型: LOCAL-本地, OSS-OSS' AFTER `file_size`;
|
||||
@@ -1,2 +0,0 @@
|
||||
-- 添加颜色字段到订单状态表
|
||||
ALTER TABLE `ec_order_status` ADD COLUMN `color` varchar(20) DEFAULT NULL COMMENT '状态颜色(十六进制,如 #1890ff)' AFTER `description`;
|
||||
@@ -1,12 +0,0 @@
|
||||
-- 同一公司下商品名称唯一(与导入并发建品一致;若已有重复 (company_id, name) 需先清理数据)
|
||||
SET @db := DATABASE();
|
||||
SET @exists := (
|
||||
SELECT COUNT(1) FROM information_schema.statistics
|
||||
WHERE table_schema = @db AND table_name = 'ec_product' AND index_name = 'uk_company_name'
|
||||
);
|
||||
SET @sql := IF(@exists = 0,
|
||||
'ALTER TABLE ec_product ADD UNIQUE INDEX uk_company_name (company_id, name)',
|
||||
'SELECT 1');
|
||||
PREPARE s FROM @sql;
|
||||
EXECUTE s;
|
||||
DEALLOCATE PREPARE s;
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
-- 同一公司下规格编码唯一(与导入并发建规格一致)
|
||||
SET @db := DATABASE();
|
||||
SET @exists := (
|
||||
SELECT COUNT(1) FROM information_schema.statistics
|
||||
WHERE table_schema = @db AND table_name = 'ec_product_spec' AND index_name = 'uk_company_spec_code'
|
||||
);
|
||||
SET @sql := IF(@exists = 0,
|
||||
'ALTER TABLE ec_product_spec ADD UNIQUE INDEX uk_company_spec_code (company_id, spec_code)',
|
||||
'SELECT 1');
|
||||
PREPARE s FROM @sql;
|
||||
EXECUTE s;
|
||||
DEALLOCATE PREPARE s;
|
||||
@@ -1,144 +0,0 @@
|
||||
-- ========================================
|
||||
-- 权限系统重构 DDL
|
||||
-- 执行时间:2026-03-30
|
||||
-- 说明:
|
||||
-- 1. sys_menu_permission_map → sys_menu_permission(重命名+简化,去掉 id 主键和 create_by)
|
||||
-- 2. org_company_menu → sys_company_menu(重命名+删除冗余字段)
|
||||
-- 3. org_position_company_menu_map → org_position_menu(重命名+去掉 status)
|
||||
-- 4. 新增 org_position_permission 表
|
||||
-- ========================================
|
||||
|
||||
-- ========================================
|
||||
-- Step 1: sys_menu_permission_map → sys_menu_permission
|
||||
-- ========================================
|
||||
|
||||
-- 1.1 创建新表 sys_menu_permission(无主键,menu_id+permission_id 联合主键)
|
||||
DROP TABLE IF EXISTS `sys_menu_permission`;
|
||||
CREATE TABLE `sys_menu_permission` (
|
||||
`menu_id` bigint unsigned NOT NULL COMMENT '菜单ID',
|
||||
`permission_id` bigint unsigned NOT NULL COMMENT '权限ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`menu_id`, `permission_id`) USING BTREE,
|
||||
KEY `idx_sys_menu_permission_permission` (`permission_id`) USING BTREE,
|
||||
CONSTRAINT `fk_sys_menu_permission_menu` FOREIGN KEY (`menu_id`) REFERENCES `sys_menu` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_menu_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `sys_permission` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='菜单与权限关联表(参考信息,非分配关系)';
|
||||
|
||||
-- 1.2 从旧表迁移数据到新表
|
||||
INSERT INTO `sys_menu_permission` (`menu_id`, `permission_id`, `create_time`)
|
||||
SELECT `menu_id`, `permission_id`, `create_time`
|
||||
FROM `sys_menu_permission_map`;
|
||||
|
||||
-- 1.3 验证数据
|
||||
-- SELECT COUNT(*) as old_count FROM `sys_menu_permission_map`;
|
||||
-- SELECT COUNT(*) as new_count FROM `sys_menu_permission`;
|
||||
|
||||
-- 1.4 删除旧表(确认迁移成功后再执行)
|
||||
-- DROP TABLE `sys_menu_permission_map`;
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- Step 2: org_company_menu → sys_company_menu
|
||||
-- 去掉:parent_id, custom_name, custom_title, custom_icon, custom_order
|
||||
-- ========================================
|
||||
|
||||
-- 2.1 创建新表 sys_company_menu(简化版)
|
||||
DROP TABLE IF EXISTS `sys_company_menu`;
|
||||
CREATE TABLE `sys_company_menu` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '公司ID',
|
||||
`menu_id` bigint unsigned NOT NULL COMMENT '分配的菜单ID',
|
||||
`status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '状态 (0-禁用 1-启用)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint unsigned DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `uk_sys_company_menu_company_menu` (`company_id`, `menu_id`) USING BTREE,
|
||||
KEY `fk_sys_company_menu_company` (`company_id`) USING BTREE,
|
||||
KEY `fk_sys_company_menu_menu` (`menu_id`) USING BTREE,
|
||||
CONSTRAINT `fk_sys_company_menu_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_company_menu_menu` FOREIGN KEY (`menu_id`) REFERENCES `sys_menu` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=127 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司菜单配置表(平台分配给公司的菜单)';
|
||||
|
||||
-- 2.2 从旧表迁移数据到新表(只迁移需要的字段)
|
||||
INSERT INTO `sys_company_menu` (`id`, `company_id`, `menu_id`, `status`, `create_time`, `update_time`, `create_by`, `update_by`)
|
||||
SELECT `id`, `company_id`, `menu_id`, `status`, `create_time`, `update_time`, `create_by`, `update_by`
|
||||
FROM `org_company_menu`;
|
||||
|
||||
-- 2.3 验证数据
|
||||
-- SELECT COUNT(*) as old_count FROM `org_company_menu`;
|
||||
-- SELECT COUNT(*) as new_count FROM `sys_company_menu`;
|
||||
|
||||
-- 2.4 删除旧表(确认迁移成功后再执行)
|
||||
-- DROP TABLE `org_company_menu`;
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- Step 3: org_position_company_menu_map → org_position_menu
|
||||
-- 去掉 status,menu_id 直接指向 sys_menu.id
|
||||
-- ========================================
|
||||
|
||||
-- 3.1 创建新表 org_position_menu(menu_id 直接指向 sys_menu.id)
|
||||
DROP TABLE IF EXISTS `org_position_menu`;
|
||||
CREATE TABLE `org_position_menu` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`position_id` bigint unsigned NOT NULL COMMENT '岗位ID',
|
||||
`menu_id` bigint unsigned NOT NULL COMMENT '菜单ID(对应 sys_menu.id)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `uk_org_position_menu_position_menu` (`position_id`, `menu_id`) USING BTREE,
|
||||
KEY `fk_org_position_menu_position` (`position_id`) USING BTREE,
|
||||
KEY `fk_org_position_menu_menu` (`menu_id`) USING BTREE,
|
||||
CONSTRAINT `fk_org_position_menu_position` FOREIGN KEY (`position_id`) REFERENCES `org_position` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_org_position_menu_menu` FOREIGN KEY (`menu_id`) REFERENCES `sys_menu` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='岗位菜单关联表(控制侧边栏展示)';
|
||||
|
||||
-- 3.2 迁移数据(旧表是通过 company_menu 间接关联菜单,新表直接关联 sys_menu)
|
||||
-- 旧表结构: org_position_company_menu_map (position_id, company_menu_id, status, ...)
|
||||
-- 新表结构: org_position_menu (position_id, menu_id, ...)
|
||||
-- 需要通过 company_menu_id 找到对应的 menu_id
|
||||
INSERT INTO `org_position_menu` (`position_id`, `menu_id`, `create_time`, `create_by`)
|
||||
SELECT
|
||||
ppm.position_id,
|
||||
cm.menu_id AS menu_id,
|
||||
ppm.create_time,
|
||||
ppm.create_by
|
||||
FROM `org_position_company_menu_map` ppm
|
||||
INNER JOIN `org_company_menu` cm ON ppm.company_menu_id = cm.id;
|
||||
|
||||
-- 3.3 验证数据
|
||||
-- SELECT COUNT(*) as old_count FROM `org_position_company_menu_map`;
|
||||
-- SELECT COUNT(*) as new_count FROM `org_position_menu`;
|
||||
|
||||
-- 3.4 删除旧表(确认迁移成功后再执行)
|
||||
-- DROP TABLE `org_position_company_menu_map`;
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- Step 4: 新增 org_position_permission 表
|
||||
-- ========================================
|
||||
|
||||
DROP TABLE IF EXISTS `org_position_permission`;
|
||||
CREATE TABLE `org_position_permission` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`position_id` bigint unsigned NOT NULL COMMENT '岗位ID',
|
||||
`permission_id` bigint unsigned NOT NULL COMMENT '权限ID(对应 sys_permission.id)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE KEY `uk_org_position_permission_position_permission` (`position_id`, `permission_id`) USING BTREE,
|
||||
KEY `idx_org_position_permission_position` (`position_id`) USING BTREE,
|
||||
KEY `idx_org_position_permission_permission` (`permission_id`) USING BTREE,
|
||||
CONSTRAINT `fk_org_position_permission_position` FOREIGN KEY (`position_id`) REFERENCES `org_position` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_org_position_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `sys_permission` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='岗位权限关联表(控制接口访问权限)';
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- 数据迁移完成确认后,执行以下清理:
|
||||
-- DROP TABLE IF EXISTS `sys_menu_permission_map`;
|
||||
-- DROP TABLE IF EXISTS `org_company_menu`;
|
||||
-- DROP TABLE IF EXISTS `org_position_company_menu_map`;
|
||||
-- ========================================
|
||||
@@ -1,53 +0,0 @@
|
||||
-- ========================================
|
||||
-- SQL 设计查漏补缺
|
||||
-- 时间:2026-03-31
|
||||
-- 背景:对比数据库实际表结构和设计 SQL,发现以下问题:
|
||||
-- 1. org_company_permission 表存在于数据库,但 org_design.sql 中缺失
|
||||
-- 2. media_image 表存在于数据库,但没有任何设计 SQL 包含它
|
||||
-- 3. sys_menu_permission 实际结构与 sys_design.sql 不一致
|
||||
-- ========================================
|
||||
|
||||
-- ========================================
|
||||
-- 1. org_company_permission(补充到 org_design.sql)
|
||||
-- 平台分配给公司的权限
|
||||
-- 关联:org_company ←→ sys_permission
|
||||
-- ========================================
|
||||
DROP TABLE IF EXISTS `org_company_permission`;
|
||||
CREATE TABLE `org_company_permission` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '公司ID',
|
||||
`permission_id` bigint unsigned NOT NULL COMMENT '权限ID(对应 sys_permission.id)',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_org_company_permission_company_permission` (`company_id`, `permission_id`),
|
||||
KEY `fk_org_company_permission_company` (`company_id`),
|
||||
KEY `fk_org_company_permission_permission` (`permission_id`),
|
||||
CONSTRAINT `fk_org_company_permission_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE,
|
||||
CONSTRAINT `fk_org_company_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `sys_permission` (`id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司权限配置表(平台分配给公司的权限)';
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- 2. media_image(已废弃,媒体模块不再需要,不纳入设计)
|
||||
-- ========================================
|
||||
|
||||
|
||||
-- ========================================
|
||||
-- 3. sys_menu_permission 修正(sys_design.sql 中的定义需同步)
|
||||
-- 说明:原设计 SQL 写的是"无主键,menu_id+permission_id 联合主键",
|
||||
-- 实际数据库用自增 id 做主键,(menu_id, permission_id) 做唯一索引
|
||||
-- ========================================
|
||||
-- 以下是实际数据库中的正确结构(sys_design.sql 中的定义应更新为如下):
|
||||
DROP TABLE IF EXISTS `sys_menu_permission`;
|
||||
CREATE TABLE `sys_menu_permission` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`menu_id` bigint unsigned NOT NULL COMMENT '菜单ID',
|
||||
`permission_id` bigint unsigned NOT NULL COMMENT '权限ID',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_sys_menu_permission_menu_permission` (`menu_id`, `permission_id`),
|
||||
KEY `idx_sys_menu_permission_permission` (`permission_id`) USING BTREE,
|
||||
CONSTRAINT `fk_sys_menu_permission_menu` FOREIGN KEY (`menu_id`) REFERENCES `sys_menu` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_sys_menu_permission_permission` FOREIGN KEY (`permission_id`) REFERENCES `sys_permission` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='菜单与权限关联表(参考信息,非分配关系)';
|
||||
@@ -1,123 +0,0 @@
|
||||
-- ========================================
|
||||
-- 权限系统树状结构重构
|
||||
-- 执行时间:2026-04-10
|
||||
-- 说明:
|
||||
-- 1. sys_permission 表新增 parent_id(父权限ID)、sort_order(排序)
|
||||
-- 2. type ENUM 新增 'module' 选项(模块分组)
|
||||
-- 3. 现有 41 个权限点重构为树状分类
|
||||
-- 4. parent_id 为 NULL 表示顶级模块(不可操作,仅做分组)
|
||||
-- 5. 有 parent_id 的为具体权限(可分配给职位)
|
||||
-- 6. UNIQUE KEY 改为 (code, parent_id) 允许不同父节点的模块使用相同 code
|
||||
-- ========================================
|
||||
|
||||
-- ----------------------------------------
|
||||
-- Step 1: 新增 parent_id、sort_order 字段,修改 type ENUM
|
||||
-- ----------------------------------------
|
||||
ALTER TABLE `sys_permission`
|
||||
ADD COLUMN `parent_id` BIGINT UNSIGNED NULL DEFAULT NULL COMMENT '父权限ID(NULL=顶级模块)' AFTER `id`,
|
||||
ADD COLUMN `sort_order` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '同级排序(数字越小越靠前)' AFTER `remark`;
|
||||
|
||||
ALTER TABLE `sys_permission`
|
||||
MODIFY COLUMN `type` ENUM('api','button','data','module') NOT NULL DEFAULT 'api' COMMENT '权限类型(api-接口权限,button-按钮权限,data-数据权限,module-模块分组)';
|
||||
|
||||
-- 去掉原来的 uk_code 唯一约束(code 不能为 NULL),改为 (code, parent_id)
|
||||
ALTER TABLE `sys_permission` DROP INDEX `uk_code`;
|
||||
|
||||
ALTER TABLE `sys_permission`
|
||||
ADD UNIQUE KEY `uk_code_parent` (`code`, `parent_id`);
|
||||
|
||||
ALTER TABLE `sys_permission`
|
||||
ADD CONSTRAINT `fk_sys_permission_parent` FOREIGN KEY (`parent_id`)
|
||||
REFERENCES `sys_permission` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `sys_permission`
|
||||
ADD INDEX `idx_parent_id` (`parent_id`),
|
||||
ADD INDEX `idx_sort_order` (`sort_order`);
|
||||
|
||||
-- ----------------------------------------
|
||||
-- Step 2: 插入顶级模块(parent_id = NULL,code 用 MODULE: 前缀避免冲突)
|
||||
-- ----------------------------------------
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `code`, `type`, `sort_order`, `status`, `remark`, `create_time`) VALUES
|
||||
(100, NULL, '系统管理', 'MODULE:system', 'module', 10, 1, '系统管理模块(平台超管专用)', NOW()),
|
||||
(101, NULL, '组织架构', 'MODULE:org', 'module', 20, 1, '组织架构模块(公司管理)', NOW()),
|
||||
(102, NULL, '电商业务', 'MODULE:ecom', 'module', 30, 1, '电商业务模块', NOW()),
|
||||
(103, NULL, '数据操作', 'MODULE:data', 'module', 40, 1, '数据操作模块', NOW());
|
||||
|
||||
-- ----------------------------------------
|
||||
-- Step 3: 插入子模块(parent_id → 顶级模块,type=module)
|
||||
-- ----------------------------------------
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `code`, `type`, `sort_order`, `status`, `create_time`) VALUES
|
||||
-- 100 系统管理 子模块
|
||||
(110, 100, '菜单权限', 'system:menu', 'module', 100, 1, NOW()),
|
||||
(111, 100, '用户权限', 'system:user', 'module', 110, 1, NOW()),
|
||||
(112, 100, '职位权限', 'system:position', 'module', 120, 1, NOW()),
|
||||
(113, 100, '公司权限', 'system:company', 'module', 130, 1, NOW()),
|
||||
(114, 100, '权限管理', 'system:permission', 'module', 140, 1, NOW()),
|
||||
-- 101 组织架构 子模块
|
||||
(120, 101, '公司管理', 'org:company', 'module', 200, 1, NOW()),
|
||||
(121, 101, '部门管理', 'org:department', 'module', 210, 1, NOW()),
|
||||
(122, 101, '职位管理', 'org:position', 'module', 220, 1, NOW()),
|
||||
(123, 101, '成员管理', 'org:member', 'module', 230, 1, NOW()),
|
||||
(124, 101, '菜单分配', 'org:company-menu', 'module', 240, 1, NOW()),
|
||||
(125, 101, '权限分配', 'org:company-permission', 'module', 250, 1, NOW()),
|
||||
-- 102 电商业务 子模块
|
||||
(130, 102, '商品管理', 'ecom:product', 'module', 300, 1, NOW()),
|
||||
(131, 102, '订单管理', 'ecom:order', 'module', 310, 1, NOW()),
|
||||
(132, 102, '店铺管理', 'ecom:shop', 'module', 320, 1, NOW()),
|
||||
-- 103 数据操作 子模块
|
||||
(140, 103, '数据导入', 'data:import-group', 'module', 400, 1, NOW()),
|
||||
(141, 103, '数据导出', 'data:export-group', 'module', 410, 1, NOW());
|
||||
|
||||
-- ----------------------------------------
|
||||
-- Step 4: 更新现有权限的 parent_id 和 sort_order
|
||||
-- ----------------------------------------
|
||||
UPDATE `sys_permission` SET `parent_id`=110, `sort_order`=11 WHERE `code`='system:menu:update';
|
||||
UPDATE `sys_permission` SET `parent_id`=110, `sort_order`=12 WHERE `code`='system:menu:create';
|
||||
UPDATE `sys_permission` SET `parent_id`=110, `sort_order`=13 WHERE `code`='system:menu:delete';
|
||||
UPDATE `sys_permission` SET `parent_id`=110, `sort_order`=14 WHERE `code`='system:menu:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=111, `sort_order`=21 WHERE `code`='system:user:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=111, `sort_order`=22 WHERE `code`='system:user:create';
|
||||
UPDATE `sys_permission` SET `parent_id`=111, `sort_order`=23 WHERE `code`='system:user:update';
|
||||
UPDATE `sys_permission` SET `parent_id`=111, `sort_order`=24 WHERE `code`='system:user:delete';
|
||||
UPDATE `sys_permission` SET `parent_id`=112, `sort_order`=31 WHERE `code`='system:position:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=113, `sort_order`=32 WHERE `code`='system:company:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=114, `sort_order`=41 WHERE `code`='system:permission:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=120, `sort_order`=201 WHERE `code`='org:company:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=120, `sort_order`=202 WHERE `code`='org:company:create';
|
||||
UPDATE `sys_permission` SET `parent_id`=120, `sort_order`=203 WHERE `code`='org:company:update';
|
||||
UPDATE `sys_permission` SET `parent_id`=120, `sort_order`=204 WHERE `code`='org:company:delete';
|
||||
UPDATE `sys_permission` SET `parent_id`=121, `sort_order`=211 WHERE `code`='org:department:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=121, `sort_order`=212 WHERE `code`='org:department:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=122, `sort_order`=221 WHERE `code`='org:position:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=122, `sort_order`=222 WHERE `code`='org:position:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=123, `sort_order`=231 WHERE `code`='org:member:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=123, `sort_order`=232 WHERE `code`='org:member:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=124, `sort_order`=241 WHERE `code`='org:company-menu:assign';
|
||||
UPDATE `sys_permission` SET `parent_id`=124, `sort_order`=242 WHERE `code`='org:position-menu:assign';
|
||||
UPDATE `sys_permission` SET `parent_id`=125, `sort_order`=251 WHERE `code`='org:company-permission:assign';
|
||||
UPDATE `sys_permission` SET `parent_id`=125, `sort_order`=252 WHERE `code`='org:position-permission:assign';
|
||||
UPDATE `sys_permission` SET `parent_id`=130, `sort_order`=301 WHERE `code`='ecom:product:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=130, `sort_order`=302 WHERE `code`='ecom:product:create';
|
||||
UPDATE `sys_permission` SET `parent_id`=130, `sort_order`=303 WHERE `code`='ecom:product:update';
|
||||
UPDATE `sys_permission` SET `parent_id`=130, `sort_order`=304 WHERE `code`='ecom:product:delete';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=311 WHERE `code`='ecom:order:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=312 WHERE `code`='ecom:order:create';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=313 WHERE `code`='ecom:order:update';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=314 WHERE `code`='ecom:order:delete';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=315 WHERE `code`='ecom:order:import';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=316 WHERE `code`='ecom:order:export';
|
||||
UPDATE `sys_permission` SET `parent_id`=131, `sort_order`=317 WHERE `code`='ecom:order:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=132, `sort_order`=321 WHERE `code`='ecom:shop:read';
|
||||
UPDATE `sys_permission` SET `parent_id`=132, `sort_order`=322 WHERE `code`='ecom:shop:manage';
|
||||
UPDATE `sys_permission` SET `parent_id`=140, `sort_order`=401 WHERE `code`='data:import';
|
||||
UPDATE `sys_permission` SET `parent_id`=141, `sort_order`=411 WHERE `code`='data:export';
|
||||
UPDATE `sys_permission` SET `parent_id`=120, `sort_order`=205 WHERE `code`='org:company:manage';
|
||||
|
||||
-- ----------------------------------------
|
||||
-- 验证查询
|
||||
-- ----------------------------------------
|
||||
-- SELECT p.id, p.code, p.name, p.parent_id, p.type, p.sort_order,
|
||||
-- pp.name as parent_name
|
||||
-- FROM sys_permission p
|
||||
-- LEFT JOIN sys_permission pp ON p.parent_id = pp.id
|
||||
-- ORDER BY p.parent_id, p.sort_order;
|
||||
Reference in New Issue
Block a user