feat: 优化bi层,提高并发处理能力

This commit is contained in:
2026-08-13 15:45:45 +08:00
parent f01249debd
commit f7e2d880e6
10 changed files with 137 additions and 61 deletions
@@ -57,7 +57,7 @@
|----|------|-----------------|
| 同步 | `order.sync.pdd.full` / `order.sync.pdd.inc` | **可并行**(独立 Redis 锁:`…:full:lock` / `…:inc:lock`) |
| 转换 | `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` |
| BI | `bi.stat.full` / `bi.stat.inc` | **同店同日互斥**(`bi:stat:lock:{company}:{shop}:{statDate}`);不同日/不同店可并行;全量持久化该日 `dbSnapshotTime` |
任务入口(全量任务 / 按日 / 增量 Job / 手动增量)均 **只投递 MQ**,由 consumer 执行;补单仍可同步执行后投递 INC 转换。
@@ -129,7 +129,7 @@ FE 打开店铺增量开关
· 在外 → 把消息里的 delta $inc 累加到 document(不按日重算)
```
全量任务运行中**不阻塞**增量 Job;转换侧靠平台更新时间幂等;BI 全量/增量同店串行,靠 Mongo `dbSnapshotTime` + 会话快照互斥。
全量任务运行中**不阻塞**增量 Job;转换侧靠平台更新时间幂等;BI 全量/增量**同店同日**互斥,靠 Mongo `dbSnapshotTime` + 日锁会话快照;不同日可并行。
---
@@ -486,25 +486,25 @@ RoutingKey:
### 6.4 增量计算与快照互斥
比较键:消息 **`internalOrderUpdateTime`** vs 文档/会话 **`dbSnapshotTime`**。
增量指标变化由**转换侧**算好放在消息里;BI 侧只做跳过判断与 Mongo `$inc`。全量/增量消息**同店串行**。
增量指标变化由**转换侧**算好放在消息里;BI 侧只做跳过判断与 Mongo `$inc`。全量/增量消息**同店同日互斥**,不同日可并行。
| 场景 | 行为 |
|------|------|
| 存在进行中的全量锁,且已暴露会话 `snapshotTime`,`internalOrderUpdateTime <= snapshotTime` | **ack 跳过** |
| 存在进行中的全量锁,且 `internalOrderUpdateTime > snapshotTime` | **延后重试**,等全量写完后再比文档 `dbSnapshotTime` |
| 无进行中全量;文档存在且 `internalOrderUpdateTime <= dbSnapshotTime` | **ack 跳过** |
| 无进行中全量;文档不存在,或 `internalOrderUpdateTime > dbSnapshotTime` | 对 shop/product/sku **`$inc` 累加消息 delta**,`computeMode=INC`,**不更新** `dbSnapshotTime`(无文档时新建,`dbSnapshotTime` 为空,仅全量填充) |
| 存在**同日**进行中的全量锁,且已暴露会话 `snapshotTime`,`internalOrderUpdateTime <= snapshotTime` | **ack 跳过** |
| 存在**同日**进行中的全量锁,且 `internalOrderUpdateTime > snapshotTime` | **延后重试**,等全量写完后再比文档 `dbSnapshotTime` |
| 无同日进行中全量;文档存在且 `internalOrderUpdateTime <= dbSnapshotTime` | **ack 跳过** |
| 无同日进行中全量;文档不存在,或 `internalOrderUpdateTime > dbSnapshotTime` | 对 shop/product/sku **`$inc` 累加消息 delta**,`computeMode=INC`,**不更新** `dbSnapshotTime`(无文档时新建,`dbSnapshotTime` 为空,仅全量填充) |
说明:
- 「快照时间范围内」= **`internalOrderUpdateTime <= dbSnapshotTime`**
- 全量进行中把 `snapshotTime` 登记到 Redis 锁元数据;落库后以 Mongo `dbSnapshotTime` 为准
- 同店串行锁;delta 累加幂等依赖「快照跳过 + 至少一次投递下的业务可接受重复风险」——必要时后续可加 messageId 去重
- 全量进行中把 `snapshotTime` 登记到**该日** Redis 锁元数据;落库后以 Mongo `dbSnapshotTime` 为准
- 锁粒度:`bi:stat:lock:{companyId}:{shopId}:{statDate}`;delta 累加幂等依赖「快照跳过 + 至少一次投递下的业务可接受重复风险」——必要时后续可加 messageId 去重
```mermaid
flowchart TD
IncMsg[BiIncCalcMessage]
Lock{全量锁存在?}
Lock{同日全量锁存在?}
CmpSession{internalOrderUpdateTime <= session.snapshotTime?}
Skip1[ack 跳过]
Delay[延迟重试]
@@ -658,11 +658,11 @@ ecom:
| BI 包结构 | 写侧子域划分 + 域内分层;禁止 `modules/bi` 根目录平铺 |
| 分析查看接口 | 日后迁 `bi`;**本文不预设目录名**;现仍留 `ec` |
| 日维度 | shop + product + sku;无月/年;无推广费/刷单 |
| 转换队列 | 全量日与增量**共用**(按平台分队列) |
| 转换队列 | 全量日 / 增量**分两个队列**;同店 FULL/INC 互斥,FULL 可按天并行 |
| BI 队列 | 全量 / 增量**分两个队列** |
| 全量计算 | MySQL consistent snapshot + 按日重算覆盖写 Mongo,写入 `dbSnapshotTime` |
| 全量计算 | MySQL consistent snapshot + 按日重算覆盖写 Mongo,写入 `dbSnapshotTime`;锁 `bi:stat:lock:{company}:{shop}:{statDate}` |
| 增量转换 | 消息带渠道主键;内部用 `platform_code + source_order_id` 定位;对比 `ec_order.platform_updated_at` vs 渠道 `pdd_updated_at`;跳过或转换并产出 delta |
| 增量计算 | 转换侧算 delta 并带 `internalOrderUpdateTime`;BI:`internalOrderUpdateTime <= dbSnapshotTime` 跳过,否则 `$inc`;全量进行中且更新更晚则延后 |
| 增量计算 | 转换侧算 delta 并带 `internalOrderUpdateTime`;BI:`internalOrderUpdateTime <= dbSnapshotTime` 跳过,否则 `$inc`;**同日**全量进行中且更新更晚则延后;不同日可并行 |
| 增量写 Mongo | `$inc` 累加,不抬高 `dbSnapshotTime` |
| 投递转换 | 全量按天 / 增量按页 publish(消息带渠道镜像主键);Listener 仅 repair |
| 转换侧快照 | **取消** Redis 全量转换快照;新旧判断落在订单行上的平台更新时间 |
@@ -9,12 +9,18 @@ import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "ecom.bi.stat")
public class BiStatProperties {
/** 全量计算锁 TTL(秒) */
/** 日计算锁 TTL(秒) */
private long lockTtlSeconds = 600;
/** 增量遇全量进行中时延迟毫秒 */
/** 遇同日锁忙时延迟毫秒 */
private long incDelayMs = 5000;
/** 增量延迟最大重试次数 */
/** 延迟最大重试次数 */
private int incMaxRetry = 20;
/** BI 全量队列消费者并发(支持 "n" 或 "m-n") */
private String fullListenerConcurrency = "2-4";
/** BI 增量队列消费者并发 */
private String incListenerConcurrency = "2-4";
}
@@ -7,15 +7,16 @@ import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* BI 同店串行锁(全量/增量共用)。
* 全量抢锁时登记会话 snapshotTime(事务快照开启时刻),供进行中的增量跳过/延后;
* 持久化的「最新全量快照时间」以 Mongo 文档 dbSnapshotTime 为准。
* BI 店+日计算锁(同日 FULL/INC 互斥;不同日可并行)。
* 全量抢锁时登记会话 snapshotTime,供同日进行中的增量跳过/延后;
* 持久化的「最新全量快照时间」以该日 Mongo 文档 dbSnapshotTime 为准。
*/
@Component
@RequiredArgsConstructor
@@ -26,9 +27,17 @@ public class BiStatComputeLock {
private final StringRedisTemplate stringRedisTemplate;
private final BiStatProperties biStatProperties;
/** 同店串行:key = companyId:shopId */
public Optional<Session> tryLock(Long companyId, Long shopId, Instant snapshotTimeOrNull) {
String key = lockKey(companyId, shopId);
/**
* 抢占 (companyId, shopId, statDate) 日锁。
*
* @param snapshotTimeOrNull 全量传入会话快照时刻;增量传 null
*/
public Optional<Session> tryLock(Long companyId, Long shopId, LocalDate statDate,
Instant snapshotTimeOrNull) {
if (companyId == null || shopId == null || statDate == null) {
return Optional.empty();
}
String key = lockKey(companyId, shopId, statDate);
String token = UUID.randomUUID().toString();
long ttl = Math.max(biStatProperties.getLockTtlSeconds(), 60);
Boolean ok = stringRedisTemplate.opsForValue()
@@ -43,16 +52,18 @@ public class BiStatComputeLock {
}
stringRedisTemplate.opsForHash().putAll(key, meta);
stringRedisTemplate.expire(key, Duration.ofSeconds(ttl));
return Optional.of(new Session(key, token, snapshotTimeOrNull));
return Optional.of(new Session(key, token, snapshotTimeOrNull, companyId, shopId, statDate));
}
public Optional<Instant> peekSessionSnapshot(Long companyId, Long shopId) {
Object v = stringRedisTemplate.opsForHash().get(lockKey(companyId, shopId), "snapshotTime");
public Optional<Instant> peekSessionSnapshot(Long companyId, Long shopId, LocalDate statDate) {
Object v = stringRedisTemplate.opsForHash()
.get(lockKey(companyId, shopId, statDate), "snapshotTime");
return parseInstant(v);
}
public boolean isLocked(Long companyId, Long shopId) {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(lockKey(companyId, shopId) + ":hold"));
public boolean isLocked(Long companyId, Long shopId, LocalDate statDate) {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(
lockKey(companyId, shopId, statDate) + ":hold"));
}
public void unlock(Session session) {
@@ -67,8 +78,8 @@ public class BiStatComputeLock {
}
}
private static String lockKey(Long companyId, Long shopId) {
return LOCK_PREFIX + companyId + ":" + shopId;
private static String lockKey(Long companyId, Long shopId, LocalDate statDate) {
return LOCK_PREFIX + companyId + ":" + shopId + ":" + statDate;
}
private static Optional<Instant> parseInstant(Object v) {
@@ -82,6 +93,7 @@ public class BiStatComputeLock {
}
}
public record Session(String key, String token, Instant snapshotTime) {
public record Session(String key, String token, Instant snapshotTime,
Long companyId, Long shopId, LocalDate statDate) {
}
}
@@ -22,7 +22,9 @@ public class BiStatFullConsumer {
private final BiStatProperties biStatProperties;
private final DelayedMqRepublisher delayedMqRepublisher;
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
@RabbitListener(
queues = OrderMqConstants.QUEUE_BI_STAT_FULL,
concurrency = "${ecom.bi.stat.full-listener-concurrency:2-4}")
public void onMessage(BiFullCalcMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getStatDate() == null) {
@@ -54,7 +56,7 @@ public class BiStatFullConsumer {
OrderMqConstants.RK_BI_STAT_FULL,
message,
biStatProperties.getIncDelayMs());
log.info("BI full 店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
message.getMessageId(), message.getShopId(), message.getRetryCount());
log.info("BI full 日锁占用,已安排延迟重投 messageId={} shopId={} statDate={} retry={}",
message.getMessageId(), message.getShopId(), message.getStatDate(), message.getRetryCount());
}
}
@@ -18,9 +18,9 @@ import java.time.OffsetDateTime;
import java.util.Optional;
/**
* BI 增量:与同店全量串行。
* 比较消息中的内部订单更新时间 vs Mongo 文档最新全量快照时间(dbSnapshotTime);
* 在快照内(≤)跳过,在外(>)才 $inc。全量进行中则按会话快照同样规则跳过或延后。
* BI 增量:与同店同日全量互斥;不同日可并行。
* 比较消息中的内部订单更新时间 vs 该日 Mongo 文档最新全量快照时间(dbSnapshotTime);
* 在快照内(≤)跳过,在外(>)才 $inc。同日全量进行中则按会话快照同样规则跳过或延后。
*/
@Slf4j
@Component
@@ -32,7 +32,9 @@ public class BiStatIncConsumer {
private final BiStatProperties biStatProperties;
private final DelayedMqRepublisher delayedMqRepublisher;
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
@RabbitListener(
queues = OrderMqConstants.QUEUE_BI_STAT_INC,
concurrency = "${ecom.bi.stat.inc-listener-concurrency:2-4}")
public void onMessage(BiIncCalcMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getStatDate() == null || message.getInternalOrderUpdateTime() == null) {
@@ -42,12 +44,12 @@ public class BiStatIncConsumer {
LocalDate statDate = LocalDate.parse(message.getStatDate());
Instant internalUpdated = message.getInternalOrderUpdateTime().toInstant();
// 全量进行中:同店串行;内部更新时间已在会话快照内则跳过,否则等全量结束后再比文档
if (computeLock.isLocked(message.getCompanyId(), message.getShopId())) {
Optional<Instant> sessionSnapshot =
computeLock.peekSessionSnapshot(message.getCompanyId(), message.getShopId());
// 同日全量进行中:内部更新时间已在会话快照内则跳过,否则等全量结束后再比文档
if (computeLock.isLocked(message.getCompanyId(), message.getShopId(), statDate)) {
Optional<Instant> sessionSnapshot = computeLock.peekSessionSnapshot(
message.getCompanyId(), message.getShopId(), statDate);
if (sessionSnapshot.isPresent() && !internalUpdated.isAfter(sessionSnapshot.get())) {
log.info("BI inc 跳过(全量会话快照内) messageId={} shopId={} statDate={}",
log.info("BI inc 跳过(同日全量会话快照内) messageId={} shopId={} statDate={}",
message.getMessageId(), message.getShopId(), statDate);
return;
}
@@ -64,7 +66,7 @@ public class BiStatIncConsumer {
}
Optional<BiStatComputeLock.Session> session =
computeLock.tryLock(message.getCompanyId(), message.getShopId(), null);
computeLock.tryLock(message.getCompanyId(), message.getShopId(), statDate, null);
if (session.isEmpty()) {
delayAndRepublish(message);
return;
@@ -111,7 +113,7 @@ public class BiStatIncConsumer {
OrderMqConstants.RK_BI_STAT_INC,
message,
biStatProperties.getIncDelayMs());
log.info("BI inc 店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
message.getMessageId(), message.getShopId(), message.getRetryCount());
log.info("BI inc 日锁占用,已安排延迟重投 messageId={} shopId={} statDate={} retry={}",
message.getMessageId(), message.getShopId(), message.getStatDate(), message.getRetryCount());
}
}
@@ -50,14 +50,14 @@ public class OrderDailyStatComputeService {
private final PlatformTransactionManager transactionManager;
/**
* 全量:同店串行锁 + MySQL 事务一致读重算;
* 将事务快照开启时间写入 Mongo 文档 dbSnapshotTime(最新全量计算快照时间)。
* 全量:店+日锁 + MySQL 事务一致读重算;
* 将事务快照开启时间写入 Mongo 文档 dbSnapshotTime(该日最新全量计算快照时间)。
*/
public boolean tryComputeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
// 快照时刻在抢锁时登记,供进行中的增量与会话快照比较
// 快照时刻在抢锁时登记,供同日进行中的增量与会话快照比较
Instant snapshotTime = Instant.now();
Optional<BiStatComputeLock.Session> sessionOpt =
computeLock.tryLock(companyId, shopId, snapshotTime);
computeLock.tryLock(companyId, shopId, statDate, snapshotTime);
if (sessionOpt.isEmpty()) {
return false;
}
@@ -82,7 +82,7 @@ public class OrderDailyStatComputeService {
*/
public boolean tryComputeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
Optional<BiStatComputeLock.Session> sessionOpt =
computeLock.tryLock(companyId, shopId, null);
computeLock.tryLock(companyId, shopId, statDate, null);
if (sessionOpt.isEmpty()) {
return false;
}
@@ -99,14 +99,16 @@ public class OrderDailyStatComputeService {
/** @deprecated 使用 {@link #tryComputeFull} */
public void computeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
if (!tryComputeFull(companyId, shopId, statDate, platformCode)) {
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
throw new IllegalStateException(
"BI 店日计算锁占用中: " + companyId + "/" + shopId + "/" + statDate);
}
}
/** @deprecated 使用 {@link #tryComputeInc} */
public void computeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
if (!tryComputeInc(companyId, shopId, statDate, platformCode)) {
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
throw new IllegalStateException(
"BI 店日计算锁占用中: " + companyId + "/" + shopId + "/" + statDate);
}
}
@@ -61,11 +61,23 @@ public class PddOrderFullSyncTaskService {
private final CurrentUserContext currentUserContext;
private final PddOrderFullSyncProgressPublisher progressPublisher;
/** 全量任务可选日历天数(含起止日,对齐 POP「近三个月」) */
public static final int FULL_SYNC_MAX_CALENDAR_DAYS = 90;
@Transactional(rollbackFor = Exception.class)
public PddOrderFullSyncTaskVO createTask(PddOrderFullSyncTaskCreateDTO dto) {
if (dto.getDateTo().isBefore(dto.getDateFrom())) {
throw new BusinessException("结束日期不能早于开始日期");
}
LocalDate today = LocalDate.now(java.time.ZoneId.of("Asia/Shanghai"));
if (dto.getDateTo().isAfter(today)) {
throw new BusinessException("结束日期不能晚于今天");
}
LocalDate earliest = today.minusDays(FULL_SYNC_MAX_CALENDAR_DAYS - 1L);
if (dto.getDateFrom().isBefore(earliest)) {
throw new BusinessException("全量同步仅支持近 " + FULL_SYNC_MAX_CALENDAR_DAYS
+ " 天(含今天):最早可选 " + earliest);
}
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
PddOrderFullSyncTaskPO active = taskMapper.selectOne(new LambdaQueryWrapper<PddOrderFullSyncTaskPO>()
@@ -195,8 +195,19 @@ public class PddOrderSyncService {
List<ChannelOrderRef> dayRefs = new ArrayList<>();
LocalDateTime dayStart = day.atStartOfDay();
LocalDateTime dayEnd = day.plusDays(1).atStartOfDay().minusSeconds(1);
// 当日:接口只能拉到当前时刻,避免把 end 开到当日 23:59:59
LocalDate today = LocalDate.now(ZONE);
if (day.equals(today)) {
LocalDateTime now = LocalDateTime.now(ZONE);
if (now.isBefore(dayEnd)) {
dayEnd = now;
}
}
long startTs = dayStart.atZone(ZONE).toEpochSecond();
long endTs = dayEnd.atZone(ZONE).toEpochSecond();
if (endTs < startTs) {
continue;
}
int page = 1;
boolean hasNext = true;
while (hasNext) {
@@ -66,6 +66,8 @@ ecom:
lock-ttl-seconds: 600
inc-delay-ms: 5000
inc-max-retry: 20
full-listener-concurrency: "2-4"
inc-listener-concurrency: "2-4"
license:
license-file: config/license.key
revocation-file: config/revoked.jti
@@ -42,6 +42,22 @@ interface Emits {
const emit = defineEmits<Emits>();
const FULL_SYNC_MAX_CALENDAR_DAYS = 90;
function fullSyncEarliest(): Dayjs {
return dayjs().startOf('day').subtract(FULL_SYNC_MAX_CALENDAR_DAYS - 1, 'day');
}
function fullSyncLatest(): Dayjs {
return dayjs().startOf('day');
}
function disabledFullSyncDate(current: Dayjs) {
if (!current) return false;
const d = current.startOf('day');
return d.isBefore(fullSyncEarliest()) || d.isAfter(fullSyncLatest());
}
const openFlag = ref(false);
const shop = ref<null | ShopVO.Info>(null);
const loading = ref(false);
@@ -50,11 +66,8 @@ const incSubmitting = ref(false);
const createSubmitting = ref(false);
const createModalOpen = ref(false);
const createMode = ref<'day' | 'range'>('range');
const confirmDate = ref<Dayjs>(dayjs().subtract(1, 'day'));
const range = ref<[Dayjs, Dayjs]>([
dayjs().subtract(90, 'day'),
dayjs().subtract(1, 'day'),
]);
const confirmDate = ref<Dayjs>(dayjs().startOf('day'));
const range = ref<[Dayjs, Dayjs]>([fullSyncEarliest(), fullSyncLatest()]);
const incremental = ref<null | PddOrderSyncVO.IncrementalStatus>(null);
const fullTasks = ref<PddOrderSyncVO.FullTask[]>([]);
let pollTimer: null | ReturnType<typeof setInterval> = null;
@@ -299,8 +312,8 @@ async function handleResumeFull(task: PddOrderSyncVO.FullTask) {
function openCreateModal() {
createMode.value = 'range';
confirmDate.value = dayjs().subtract(1, 'day');
range.value = [dayjs().subtract(90, 'day'), dayjs().subtract(1, 'day')];
confirmDate.value = fullSyncLatest();
range.value = [fullSyncEarliest(), fullSyncLatest()];
createModalOpen.value = true;
}
@@ -314,6 +327,18 @@ async function handleCreateTask() {
message.warning('请选择全量同步日期区间');
return;
}
const dateFromDayjs =
createMode.value === 'day' ? confirmDate.value : range.value[0];
const dateToDayjs =
createMode.value === 'day' ? confirmDate.value : range.value[1];
if (
disabledFullSyncDate(dateFromDayjs) ||
disabledFullSyncDate(dateToDayjs) ||
dateToDayjs.isBefore(dateFromDayjs, 'day')
) {
message.warning('日期须在近 90 天内(含今天),且结束不早于开始');
return;
}
if (hasActiveFullTask.value) {
message.warning('该店铺已有进行中的全量任务,请先等待或取消');
return;
@@ -546,24 +571,26 @@ defineExpose({ open, close: handleClose });
<Form.Item
v-if="createMode === 'range'"
label="成交日期区间"
extra="按天串行拉取;每天成功后自动进入转换与 BI 日汇聚"
extra="仅近 90 天(含今天);选到今天时,当日按当前时刻拉取。每天成功后进入转换与 BI"
>
<DatePicker.RangePicker
v-model:value="range"
class="w-full"
:allow-clear="false"
:disabled-date="disabledFullSyncDate"
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item
v-else
label="成交日期"
extra="创建单日全量任务;若进行中任务已涵盖该日则不会重复创建"
extra="仅近 90 天(含今天);选今天时按当前时刻拉取。若进行中任务已涵盖该日则不会重复创建"
>
<DatePicker
v-model:value="confirmDate"
class="w-full"
:allow-clear="false"
:disabled-date="disabledFullSyncDate"
format="YYYY-MM-DD"
/>
</Form.Item>