mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 优化拼多多转换层,提高并发能力
This commit is contained in:
@@ -56,8 +56,8 @@
|
||||
| 侧 | 队列 | 同店 full / inc |
|
||||
|----|------|-----------------|
|
||||
| 同步 | `order.sync.pdd.full` / `order.sync.pdd.inc` | **可并行**(独立 Redis 锁:`…:full:lock` / `…:inc:lock`) |
|
||||
| 转换 | `order.convert.pdd`(共用) | **串行**(`order:convert:lock:{shopId}`);增量按渠道主键定位 + `platform_updated_at` 新旧比对,**不再**写转换侧 Redis 快照 |
|
||||
| BI | `bi.stat.full` / `bi.stat.inc` | **串行**(`bi:stat:lock:{company}:{shop}`);全量持久化 `bi:stat:snapshot:…` |
|
||||
| 转换 | `order.convert.pdd.full` / `order.convert.pdd.inc` | **同店 FULL/INC 互斥**;FULL 按 `order:convert:lock:{shopId}:{day}` + 店信号量可多天并行;INC 独占 `…:inc`(要求信号量=0)。增量仍按渠道主键 + `platform_updated_at` 新旧比对 |
|
||||
| BI | `bi.stat.full` / `bi.stat.inc` | **串行**(`bi:stat:lock:{company}:{shop}`);全量持久化 `dbSnapshotTime` |
|
||||
|
||||
任务入口(全量任务 / 按日 / 增量 Job / 手动增量)均 **只投递 MQ**,由 consumer 执行;补单仍可同步执行后投递 INC 转换。
|
||||
|
||||
@@ -71,21 +71,24 @@ flowchart LR
|
||||
FullTask[FullSyncTask]
|
||||
IncJob[IncrementalSync]
|
||||
ChSync[ChannelDayOrIncSync]
|
||||
ConvQ[ConvertQueue_shared]
|
||||
Conv[ChannelConvertConsumer]
|
||||
ConvFullQ[ConvertFullQueue]
|
||||
ConvIncQ[ConvertIncQueue]
|
||||
Conv[ChannelConvertConsumers]
|
||||
EcOrder[ec_order]
|
||||
FullCalcQ[BiFullCalcQueue]
|
||||
IncCalcQ[BiIncCalcQueue]
|
||||
BiFull[BiFullConsumer]
|
||||
BiInc[BiIncConsumer]
|
||||
Mongo[(MongoDailyAgg)]
|
||||
Mongo[(MongoDailyStats)]
|
||||
|
||||
FE -->|create_full_task| FullTask
|
||||
FE -->|toggle_inc| IncJob
|
||||
FullTask -->|per_day| ChSync
|
||||
FullTask -->|per_day_parallel| ChSync
|
||||
IncJob --> ChSync
|
||||
ChSync -->|day_done / page_done| ConvQ
|
||||
ConvQ --> Conv
|
||||
ChSync -->|FULL_DAY| ConvFullQ
|
||||
ChSync -->|INC| ConvIncQ
|
||||
ConvFullQ --> Conv
|
||||
ConvIncQ --> Conv
|
||||
Conv --> EcOrder
|
||||
Conv -->|full_day_done| FullCalcQ
|
||||
Conv -->|per_order_delta| IncCalcQ
|
||||
@@ -99,10 +102,10 @@ flowchart LR
|
||||
|
||||
```
|
||||
FE 创建全量任务(shop, dateFrom, dateTo) // 默认近 90 天
|
||||
→ 按天串行同步 channel_pdd_*
|
||||
→ 按天拆消息并行同步 channel_pdd_*(受店级并行上限)
|
||||
→ 每同步完 1 天 → publish OrderConvertMessage(
|
||||
mode=FULL_DAY, statDate=day, orders=[{channelOrderId}, ...])
|
||||
→ Convert:开事务批量 channel → ec_order(写入 platform_updated_at)
|
||||
mode=FULL_DAY, statDate=day, orders=[{channelOrderId}, ...]) → order.convert.pdd.full
|
||||
→ Convert:日锁+信号量;开事务批量 channel → ec_order(写入 platform_updated_at)
|
||||
→ publish BiFullCalcMessage(company, shop, statDate)
|
||||
→ BI:开事务快照按日重算 → 写 Mongo,document 记录 dbSnapshotTime
|
||||
```
|
||||
@@ -114,8 +117,8 @@ FE 打开店铺增量开关
|
||||
→ IncrementalJob 扫 enabled 店铺
|
||||
→ doIncremental:按页 upsert channel_pdd_*
|
||||
→ 每同步完一页 → publish OrderConvertMessage(
|
||||
mode=INC, orders=[{channelOrderId}, ...])
|
||||
→ Convert:按渠道主键查镜像;内部单用 platform_code + source_order_id 定位
|
||||
mode=INC, orders=[{channelOrderId}, ...]) → order.convert.pdd.inc
|
||||
→ Convert:同店独占(与 FULL 互斥);按渠道主键查镜像;内部单用 platform_code + source_order_id 定位
|
||||
· 内部无此单 → 新增并算贡献差发 BI inc
|
||||
· 内部已有:channel.pdd_updated_at 不晚于 ec_order.platform_updated_at → 跳过
|
||||
· 渠道更新时间更新 → 覆盖转换;对比转换前后贡献,算出各聚合字段加减量
|
||||
@@ -215,8 +218,12 @@ FE 打开店铺增量开关
|
||||
| 名称 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `ecom.order.topic` | Topic Exchange | 订单管线统一交换机 |
|
||||
| `order.convert.pdd` | Queue | PDD 转换队列(全量日 + 增量共用) |
|
||||
| `order.convert.pdd.dlq` | Queue | 转换死信 |
|
||||
| `order.convert.pdd.full` | Queue | PDD 全量日转换 |
|
||||
| `order.convert.pdd.full.dlq` | Queue | 全量转换死信 |
|
||||
| `order.convert.pdd.inc` | Queue | PDD 增量转换 |
|
||||
| `order.convert.pdd.inc.dlq` | Queue | 增量转换死信 |
|
||||
| `order.convert.pdd` | Queue | **遗留**共用队列(仅排水转发到 full/inc) |
|
||||
| `order.convert.pdd.dlq` | Queue | 遗留转换死信 |
|
||||
| `bi.stat.full` | Queue | BI 全日重算 |
|
||||
| `bi.stat.full.dlq` | Queue | 全量计算死信 |
|
||||
| `bi.stat.inc` | Queue | BI 增量 delta 累加 |
|
||||
@@ -226,7 +233,9 @@ RoutingKey:
|
||||
|
||||
| Key | 绑定队列 |
|
||||
|-----|----------|
|
||||
| `order.convert.pdd` | `order.convert.pdd` |
|
||||
| `order.convert.pdd.full` | `order.convert.pdd.full` |
|
||||
| `order.convert.pdd.inc` | `order.convert.pdd.inc` |
|
||||
| `order.convert.pdd` | `order.convert.pdd`(遗留排水) |
|
||||
| `bi.stat.full` | `bi.stat.full` |
|
||||
| `bi.stat.inc` | `bi.stat.inc` |
|
||||
|
||||
@@ -320,8 +329,10 @@ RoutingKey:
|
||||
|
||||
| 组件 | 职责 |
|
||||
|------|------|
|
||||
| `PddOrderConvertMqPublisher` | sync 成功后发 `OrderConvertMessage` |
|
||||
| `PddOrderConvertConsumer` | 消费 `order.convert.pdd` |
|
||||
| `PddOrderConvertPublisher` | sync 成功后发 `OrderConvertMessage`(full/inc 分队列) |
|
||||
| `PddOrderConvertFullConsumer` | 消费 `order.convert.pdd.full`(日锁+信号量) |
|
||||
| `PddOrderConvertIncConsumer` | 消费 `order.convert.pdd.inc`(同店独占) |
|
||||
| `PddOrderConvertLegacyDrainConsumer` | 旧共用队列排水转发 |
|
||||
| `PddOrderConvertService` | `channel_pdd_order(+item)` → `ec_order(+item)` |
|
||||
| `PddOrderStatusMapper` | PDD 状态整型 → 内部 `OrderStatus` |
|
||||
| `PddBiCalcPublisher` | 转换完成后发 `bi.stat.full` / `bi.stat.inc` |
|
||||
|
||||
+14
@@ -15,8 +15,22 @@ public final class OrderMqConstants {
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC_DLQ = "order.sync.pdd.inc.dlq";
|
||||
|
||||
public static final String RK_ORDER_CONVERT_PDD_FULL = "order.convert.pdd.full";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_FULL = "order.convert.pdd.full";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_FULL_DLQ = "order.convert.pdd.full.dlq";
|
||||
|
||||
public static final String RK_ORDER_CONVERT_PDD_INC = "order.convert.pdd.inc";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_INC = "order.convert.pdd.inc";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_INC_DLQ = "order.convert.pdd.inc.dlq";
|
||||
|
||||
/** @deprecated 已拆为 full/inc;保留供旧队列排水 */
|
||||
@Deprecated
|
||||
public static final String RK_ORDER_CONVERT_PDD = "order.convert.pdd";
|
||||
/** @deprecated 已拆为 full/inc;保留供旧队列排水 */
|
||||
@Deprecated
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD = "order.convert.pdd";
|
||||
/** @deprecated */
|
||||
@Deprecated
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_DLQ = "order.convert.pdd.dlq";
|
||||
|
||||
public static final String RK_BI_STAT_FULL = "bi.stat.full";
|
||||
|
||||
+41
@@ -43,6 +43,47 @@ public class RabbitBiConfig {
|
||||
return new TopicExchange(OrderMqConstants.EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderConvertPddFullBinding(Queue orderConvertPddFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderConvertPddFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderConvertPddIncBinding(Queue orderConvertPddIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderConvertPddIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD_INC);
|
||||
}
|
||||
|
||||
/** 旧共用队列:仅排水,新消息不再写入 */
|
||||
@Bean
|
||||
public Queue orderConvertPddQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 订单转换编排:同店按天并行、FULL/INC 互斥、listener 并发与忙等待重投。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "pdd.order-convert")
|
||||
public class PddOrderConvertProperties {
|
||||
|
||||
/** 同店 FULL_DAY 同时并行的统计日上限 */
|
||||
private int maxParallelDaysPerShop = 2;
|
||||
|
||||
/** 日锁 / INC 锁 TTL(秒) */
|
||||
private long lockTtlSeconds = 600;
|
||||
|
||||
/** FULL 转换队列消费者并发(支持 "n" 或 "m-n") */
|
||||
private String fullListenerConcurrency = "2-4";
|
||||
|
||||
/** INC 转换队列消费者并发 */
|
||||
private String incListenerConcurrency = "2-4";
|
||||
|
||||
/** 店锁/信号量忙时延迟重投毫秒 */
|
||||
private long busyDelayMs = 5000;
|
||||
|
||||
/** 忙等待最大重试次数 */
|
||||
private int busyMaxRetry = 20;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.config.PddOrderConvertProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock.OrderConvertShopLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddOrderConvertService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* FULL_DAY 转换:日锁 + 店信号量;与同店 INC 互斥。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertFullConsumer {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final PddOrderConvertService convertService;
|
||||
private final OrderConvertShopLock convertShopLock;
|
||||
private final PddOrderConvertProperties convertProperties;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
|
||||
@RabbitListener(
|
||||
queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL,
|
||||
concurrency = "${pdd.order-convert.full-listener-concurrency:2-4}")
|
||||
public void onMessage(OrderConvertMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getMode() != OrderConvertMode.FULL_DAY || message.getStatDate() == null) {
|
||||
log.warn("FULL 转换消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
LocalDate day;
|
||||
try {
|
||||
day = LocalDate.parse(message.getStatDate());
|
||||
} catch (Exception e) {
|
||||
log.warn("FULL 转换消息 statDate 非法: {}", message.getStatDate());
|
||||
return;
|
||||
}
|
||||
log.info("收到 FULL 转换消息 shopId={} statDate={} orders={} messageId={}",
|
||||
message.getShopId(), day,
|
||||
message.getOrders() != null ? message.getOrders().size() : 0, message.getMessageId());
|
||||
|
||||
Optional<OrderConvertShopLock.Session> sessionOpt =
|
||||
convertShopLock.tryLockFullDay(message.getShopId(), day);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
OrderConvertShopLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
convertService.convert(message);
|
||||
} finally {
|
||||
convertShopLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
private void delayAndRepublish(OrderConvertMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= convertProperties.getBusyMaxRetry()) {
|
||||
throw new IllegalStateException("FULL 转换延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_ORDER_CONVERT_PDD_FULL,
|
||||
message,
|
||||
convertProperties.getBusyDelayMs());
|
||||
log.info("FULL 转换锁忙,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
+20
-14
@@ -6,8 +6,9 @@ import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.config.PddOrderConvertProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock.OrderConvertShopLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddOrderConvertService;
|
||||
|
||||
@@ -15,30 +16,35 @@ import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* INC 转换:同店独占;与任意 FULL_DAY 互斥。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertConsumer {
|
||||
public class PddOrderConvertIncConsumer {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final PddOrderConvertService convertService;
|
||||
private final OrderConvertShopLock convertShopLock;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final PddOrderConvertProperties convertProperties;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
@RabbitListener(
|
||||
queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC,
|
||||
concurrency = "${pdd.order-convert.inc-listener-concurrency:2-4}")
|
||||
public void onMessage(OrderConvertMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getMode() == null) {
|
||||
log.warn("转换消息非法: {}", message);
|
||||
|| message.getMode() != OrderConvertMode.INC) {
|
||||
log.warn("INC 转换消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
log.info("收到转换消息 mode={} shopId={} statDate={} orders={} messageId={}",
|
||||
message.getMode(), message.getShopId(), message.getStatDate(),
|
||||
log.info("收到 INC 转换消息 shopId={} orders={} messageId={}",
|
||||
message.getShopId(),
|
||||
message.getOrders() != null ? message.getOrders().size() : 0, message.getMessageId());
|
||||
|
||||
Optional<OrderConvertShopLock.Session> sessionOpt = convertShopLock.tryLock(message.getShopId());
|
||||
Optional<OrderConvertShopLock.Session> sessionOpt = convertShopLock.tryLockInc(message.getShopId());
|
||||
if (sessionOpt.isEmpty()) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
@@ -53,17 +59,17 @@ public class PddOrderConvertConsumer {
|
||||
|
||||
private void delayAndRepublish(OrderConvertMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("转换延迟重试超限: " + message.getMessageId());
|
||||
if (retry >= convertProperties.getBusyMaxRetry()) {
|
||||
throw new IllegalStateException("INC 转换延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_ORDER_CONVERT_PDD,
|
||||
OrderMqConstants.RK_ORDER_CONVERT_PDD_INC,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("转换店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
convertProperties.getBusyDelayMs());
|
||||
log.info("INC 转换锁忙,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
|
||||
/**
|
||||
* 旧共用队列排水:按 mode 转发到 full/inc 新队列后丢弃本消息。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderConvertLegacyDrainConsumer {
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
public void onMessage(OrderConvertMessage message) {
|
||||
if (message == null || message.getMode() == null) {
|
||||
log.warn("旧转换队列消息非法,丢弃: {}", message);
|
||||
return;
|
||||
}
|
||||
String rk = message.getMode() == OrderConvertMode.FULL_DAY
|
||||
? OrderMqConstants.RK_ORDER_CONVERT_PDD_FULL
|
||||
: OrderMqConstants.RK_ORDER_CONVERT_PDD_INC;
|
||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, rk, message);
|
||||
log.info("旧转换队列已转发 mode={} shopId={} messageId={} -> {}",
|
||||
message.getMode(), message.getShopId(), message.getMessageId(), rk);
|
||||
}
|
||||
}
|
||||
+178
-17
@@ -1,50 +1,211 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.config.PddOrderConvertProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 转换侧同店串行锁(全量日 / 增量共用一把锁)。
|
||||
* 转换侧并发控制:
|
||||
* <ul>
|
||||
* <li>FULL_DAY:日锁 {@code order:convert:lock:{shopId}:{day}} + 店信号量(容量=maxParallelDays)</li>
|
||||
* <li>INC:独占锁 {@code order:convert:lock:{shopId}:inc},要求信号量为 0</li>
|
||||
* <li>同店 FULL 与 INC 互斥;同店多天 FULL 可并行(受信号量限制)</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OrderConvertShopLock {
|
||||
|
||||
private static final String LOCK_PREFIX = "order:convert:lock:";
|
||||
private static final long LOCK_TTL_SECONDS = 600;
|
||||
private static final String DAY_LOCK_PREFIX = "order:convert:lock:";
|
||||
private static final String SEM_PREFIX = "order:convert:sem:";
|
||||
private static final String INC_SUFFIX = ":inc";
|
||||
|
||||
private static final DefaultRedisScript<Long> ACQUIRE_FULL_SCRIPT = new DefaultRedisScript<>(
|
||||
"""
|
||||
local incKey = KEYS[1]
|
||||
local dayKey = KEYS[2]
|
||||
local semKey = KEYS[3]
|
||||
local dayToken = ARGV[1]
|
||||
local limit = tonumber(ARGV[2])
|
||||
local ttl = tonumber(ARGV[3])
|
||||
if redis.call('EXISTS', incKey) == 1 then
|
||||
return -1
|
||||
end
|
||||
if not redis.call('SET', dayKey, dayToken, 'NX', 'EX', ttl) then
|
||||
return -2
|
||||
end
|
||||
if redis.call('EXISTS', incKey) == 1 then
|
||||
redis.call('DEL', dayKey)
|
||||
return -1
|
||||
end
|
||||
local current = tonumber(redis.call('GET', semKey) or '0')
|
||||
if current >= limit then
|
||||
redis.call('DEL', dayKey)
|
||||
return -3
|
||||
end
|
||||
current = redis.call('INCR', semKey)
|
||||
redis.call('EXPIRE', semKey, ttl)
|
||||
if redis.call('EXISTS', incKey) == 1 then
|
||||
current = redis.call('DECR', semKey)
|
||||
if current <= 0 then
|
||||
redis.call('DEL', semKey)
|
||||
end
|
||||
redis.call('DEL', dayKey)
|
||||
return -1
|
||||
end
|
||||
return current
|
||||
""",
|
||||
Long.class);
|
||||
|
||||
private static final DefaultRedisScript<Long> RELEASE_FULL_SCRIPT = new DefaultRedisScript<>(
|
||||
"""
|
||||
local dayKey = KEYS[1]
|
||||
local semKey = KEYS[2]
|
||||
local dayToken = ARGV[1]
|
||||
local current = redis.call('GET', dayKey)
|
||||
if current == dayToken then
|
||||
redis.call('DEL', dayKey)
|
||||
end
|
||||
local sem = tonumber(redis.call('GET', semKey) or '0')
|
||||
if sem <= 0 then
|
||||
redis.call('DEL', semKey)
|
||||
return 0
|
||||
end
|
||||
sem = redis.call('DECR', semKey)
|
||||
if sem <= 0 then
|
||||
redis.call('DEL', semKey)
|
||||
return 0
|
||||
end
|
||||
return sem
|
||||
""",
|
||||
Long.class);
|
||||
|
||||
private static final DefaultRedisScript<Long> ACQUIRE_INC_SCRIPT = new DefaultRedisScript<>(
|
||||
"""
|
||||
local incKey = KEYS[1]
|
||||
local semKey = KEYS[2]
|
||||
local incToken = ARGV[1]
|
||||
local ttl = tonumber(ARGV[2])
|
||||
if not redis.call('SET', incKey, incToken, 'NX', 'EX', ttl) then
|
||||
return -2
|
||||
end
|
||||
local sem = tonumber(redis.call('GET', semKey) or '0')
|
||||
if sem > 0 then
|
||||
redis.call('DEL', incKey)
|
||||
return -1
|
||||
end
|
||||
return 1
|
||||
""",
|
||||
Long.class);
|
||||
|
||||
private static final DefaultRedisScript<Long> RELEASE_INC_SCRIPT = new DefaultRedisScript<>(
|
||||
"""
|
||||
local incKey = KEYS[1]
|
||||
local incToken = ARGV[1]
|
||||
local current = redis.call('GET', incKey)
|
||||
if current == incToken then
|
||||
redis.call('DEL', incKey)
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
""",
|
||||
Long.class);
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final PddOrderConvertProperties convertProperties;
|
||||
|
||||
public Optional<Session> tryLock(Long shopId) {
|
||||
String key = LOCK_PREFIX + shopId;
|
||||
String token = UUID.randomUUID().toString();
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key, token, Duration.ofSeconds(LOCK_TTL_SECONDS));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
public Optional<Session> tryLockFullDay(Long shopId, LocalDate day) {
|
||||
if (shopId == null || day == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new Session(key, token));
|
||||
String dayToken = UUID.randomUUID().toString();
|
||||
int limit = Math.max(convertProperties.getMaxParallelDaysPerShop(), 1);
|
||||
long ttl = Math.max(convertProperties.getLockTtlSeconds(), 60);
|
||||
Long result = stringRedisTemplate.execute(
|
||||
ACQUIRE_FULL_SCRIPT,
|
||||
Arrays.asList(incKey(shopId), dayKey(shopId, day), semKey(shopId)),
|
||||
dayToken,
|
||||
String.valueOf(limit),
|
||||
String.valueOf(ttl));
|
||||
if (result == null || result < 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(Session.fullDay(shopId, day, dayToken));
|
||||
}
|
||||
|
||||
public boolean isLocked(Long shopId) {
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(LOCK_PREFIX + shopId));
|
||||
public Optional<Session> tryLockInc(Long shopId) {
|
||||
if (shopId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String incToken = UUID.randomUUID().toString();
|
||||
long ttl = Math.max(convertProperties.getLockTtlSeconds(), 60);
|
||||
Long result = stringRedisTemplate.execute(
|
||||
ACQUIRE_INC_SCRIPT,
|
||||
Arrays.asList(incKey(shopId), semKey(shopId)),
|
||||
incToken,
|
||||
String.valueOf(ttl));
|
||||
if (result == null || result < 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(Session.inc(shopId, incToken));
|
||||
}
|
||||
|
||||
public void unlock(Session session) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
String current = stringRedisTemplate.opsForValue().get(session.key());
|
||||
if (session.token().equals(current)) {
|
||||
stringRedisTemplate.delete(session.key());
|
||||
try {
|
||||
if (session.mode() == Mode.FULL_DAY) {
|
||||
stringRedisTemplate.execute(
|
||||
RELEASE_FULL_SCRIPT,
|
||||
Arrays.asList(dayKey(session.shopId(), session.day()), semKey(session.shopId())),
|
||||
session.token());
|
||||
} else {
|
||||
stringRedisTemplate.execute(
|
||||
RELEASE_INC_SCRIPT,
|
||||
Collections.singletonList(incKey(session.shopId())),
|
||||
session.token());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("释放转换锁失败 shopId={} mode={}: {}",
|
||||
session.shopId(), session.mode(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public record Session(String key, String token) {
|
||||
private static String dayKey(Long shopId, LocalDate day) {
|
||||
return DAY_LOCK_PREFIX + shopId + ":" + day;
|
||||
}
|
||||
|
||||
private static String incKey(Long shopId) {
|
||||
return DAY_LOCK_PREFIX + shopId + INC_SUFFIX;
|
||||
}
|
||||
|
||||
private static String semKey(Long shopId) {
|
||||
return SEM_PREFIX + shopId;
|
||||
}
|
||||
|
||||
public enum Mode {
|
||||
FULL_DAY,
|
||||
INC
|
||||
}
|
||||
|
||||
public record Session(Long shopId, Mode mode, LocalDate day, String token) {
|
||||
static Session fullDay(Long shopId, LocalDate day, String token) {
|
||||
return new Session(shopId, Mode.FULL_DAY, day, token);
|
||||
}
|
||||
|
||||
static Session inc(Long shopId, String token) {
|
||||
return new Session(shopId, Mode.INC, null, token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -41,7 +41,7 @@ public class PddOrderConvertPublisher {
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD_FULL, msg);
|
||||
log.info("已投递 FULL_DAY 转换消息 shopId={} statDate={} orders={}",
|
||||
shopId, statDate, orders != null ? orders.size() : 0);
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class PddOrderConvertPublisher {
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD_INC, msg);
|
||||
log.info("已投递 INC 转换消息 shopId={} orders={}", shopId, orders.size());
|
||||
}
|
||||
|
||||
|
||||
@@ -58,3 +58,12 @@ pdd:
|
||||
# Rabbit 消费者并发(多店并行)
|
||||
full-listener-concurrency: "2-4"
|
||||
inc-listener-concurrency: "2-4"
|
||||
|
||||
# 订单转换:同店 FULL 按天并行;FULL/INC 拆队列且同店互斥
|
||||
order-convert:
|
||||
max-parallel-days-per-shop: 2
|
||||
lock-ttl-seconds: 600
|
||||
full-listener-concurrency: "2-4"
|
||||
inc-listener-concurrency: "2-4"
|
||||
busy-delay-ms: 5000
|
||||
busy-max-retry: 20
|
||||
|
||||
Reference in New Issue
Block a user