mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
feat: 完成初版拼多多订单同步
This commit is contained in:
-39
@@ -1,39 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service;
|
||||
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
import com.pdd.pop.sdk.http.PopAccessTokenClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
|
||||
|
||||
/**
|
||||
* 拼多多 POP SDK 客户端工厂
|
||||
*/
|
||||
@Component
|
||||
public class PddPopClientFactory {
|
||||
|
||||
private final PddOAuthProperties properties;
|
||||
|
||||
public PddPopClientFactory(PddOAuthProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public PopAccessTokenClient createAccessTokenClient() {
|
||||
assertConfigured();
|
||||
return new PopAccessTokenClient(properties.getClientId(), properties.getClientSecret());
|
||||
}
|
||||
|
||||
public PopClient createHttpClient() {
|
||||
assertConfigured();
|
||||
return new PopHttpClient(properties.getClientId(), properties.getClientSecret());
|
||||
}
|
||||
|
||||
private void assertConfigured() {
|
||||
if (!StringUtils.hasText(properties.getClientId())
|
||||
|| !StringUtils.hasText(properties.getClientSecret())) {
|
||||
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-37
@@ -5,9 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.pdd.pop.sdk.http.PopAccessTokenClient;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddMallInfoGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
|
||||
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -22,7 +19,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper.PddAuthMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddAuthService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddPopClientFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopClientFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.mall.PddMallApiSnapshot;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.mall.PddMallPopApiClient;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
|
||||
@@ -51,6 +50,7 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
|
||||
private final PddOAuthProperties properties;
|
||||
private final PddPopClientFactory popClientFactory;
|
||||
private final PddMallPopApiClient mallPopApiClient;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PddAuthMapper pddAuthMapper;
|
||||
@@ -61,6 +61,7 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
|
||||
public PddAuthServiceImpl(PddOAuthProperties properties,
|
||||
PddPopClientFactory popClientFactory,
|
||||
PddMallPopApiClient mallPopApiClient,
|
||||
StringRedisTemplate stringRedisTemplate,
|
||||
CurrentUserContext currentUserContext,
|
||||
PddAuthMapper pddAuthMapper,
|
||||
@@ -70,6 +71,7 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
ObjectMapper objectMapper) {
|
||||
this.properties = properties;
|
||||
this.popClientFactory = popClientFactory;
|
||||
this.mallPopApiClient = mallPopApiClient;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.pddAuthMapper = pddAuthMapper;
|
||||
@@ -171,8 +173,13 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
}
|
||||
|
||||
PddAuthPO auth = upsertAuth(companyId, tokenResponse);
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo = fetchMallInfo(tokenResponse.getAccessToken());
|
||||
Long mallId = resolveMallId(tokenResponse.getOwnerId(), mallInfo);
|
||||
Long tentativeMallId = parseLongOrNull(tokenResponse.getOwnerId());
|
||||
if (tentativeMallId == null) {
|
||||
return buildResultHtml(false, "无法解析拼多多店铺 owner_id");
|
||||
}
|
||||
PddMallApiSnapshot mallInfo = mallPopApiClient.getMallInfoOrNull(
|
||||
tentativeMallId, tokenResponse.getAccessToken());
|
||||
Long mallId = resolveMallId(tentativeMallId, mallInfo);
|
||||
if (mallId == null) {
|
||||
return buildResultHtml(false, "无法解析拼多多店铺 mall_id");
|
||||
}
|
||||
@@ -258,38 +265,13 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用 pdd.mall.info.get 拉取拼多多店铺详情;失败时返回 null(由调用方用 owner 信息兜底)。
|
||||
* 解析 mall_id:优先使用 mall.info 返回值,否则使用 owner_id 解析值。
|
||||
*/
|
||||
private PddMallInfoGetResponse.MallInfoGetResponse fetchMallInfo(String accessToken) {
|
||||
try {
|
||||
PopClient client = popClientFactory.createHttpClient();
|
||||
PddMallInfoGetResponse response = client.syncInvoke(new PddMallInfoGetRequest(), accessToken);
|
||||
if (response == null) {
|
||||
return null;
|
||||
}
|
||||
if (response.getErrorResponse() != null) {
|
||||
log.warn("pdd.mall.info.get 失败: {}", response.getErrorResponse().getErrorMsg());
|
||||
return null;
|
||||
}
|
||||
return response.getMallInfoGetResponse();
|
||||
} catch (Exception e) {
|
||||
log.warn("调用 pdd.mall.info.get 异常: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 mall_id:优先使用 mall.info 返回值,否则将 owner_id 解析为 Long。
|
||||
*/
|
||||
private Long resolveMallId(String ownerId, PddMallInfoGetResponse.MallInfoGetResponse mallInfo) {
|
||||
private Long resolveMallId(Long ownerMallId, PddMallApiSnapshot mallInfo) {
|
||||
if (mallInfo != null && mallInfo.getMallId() != null) {
|
||||
return mallInfo.getMallId();
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(ownerId.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
return ownerMallId;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -298,7 +280,7 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
private void upsertPddShop(Long companyId,
|
||||
Long authId,
|
||||
Long mallId,
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
|
||||
PddMallApiSnapshot mallInfo,
|
||||
String ownerName) {
|
||||
LambdaQueryWrapper<PddShopPO> byMall = new LambdaQueryWrapper<>();
|
||||
byMall.eq(PddShopPO::getCompanyId, companyId).eq(PddShopPO::getMallId, mallId);
|
||||
@@ -355,7 +337,7 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
Long userId,
|
||||
Long shopId,
|
||||
Long mallId,
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
|
||||
PddMallApiSnapshot mallInfo,
|
||||
String ownerName) {
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
@@ -478,8 +460,15 @@ public class PddAuthServiceImpl implements PddAuthService {
|
||||
if (value instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
return parseLongOrNull(String.valueOf(value));
|
||||
}
|
||||
|
||||
private static Long parseLongOrNull(String text) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(String.valueOf(value));
|
||||
return Long.parseLong(text.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 订单同步编排配置:游标重叠、锁、定时任务;不含 POP 出站限流。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "pdd.order-sync")
|
||||
public class PddOrderSyncProperties {
|
||||
|
||||
/** 增量窗口重叠秒数 */
|
||||
private int overlapSeconds = 120;
|
||||
|
||||
/** 店铺同步锁 TTL(秒) */
|
||||
private long lockTtlSeconds = 600;
|
||||
|
||||
/** 增量 Job cron */
|
||||
private String incrementalCron = "0 */5 * * * ?";
|
||||
|
||||
/** 是否启用定时增量 */
|
||||
private boolean incrementalJobEnabled = true;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto.PddOrderRepairDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.vo.PddOrderSyncResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.service.PddOrderSyncService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 拼多多订单同步(手动触发)。落库仅 ec_pdd_*,不写内部 ec_order。
|
||||
*/
|
||||
@Tag(name = "拼多多-订单同步", description = "按天回补 / 增量 / 补单")
|
||||
@RestController
|
||||
@RequestMapping("/ec/pdd/order/sync")
|
||||
public class PddOrderSyncController {
|
||||
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
|
||||
public PddOrderSyncController(PddOrderSyncService pddOrderSyncService) {
|
||||
this.pddOrderSyncService = pddOrderSyncService;
|
||||
}
|
||||
|
||||
@Operation(summary = "按成交日同步一天", description = "调用 pdd.order.list.get,按 confirm_time 拉取指定自然日订单并 upsert")
|
||||
@PostMapping("/day")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> syncDay(@Valid @RequestBody PddOrderSyncDayDTO dto) {
|
||||
return ApiResponse.success("同步完成", pddOrderSyncService.syncByConfirmDate(dto));
|
||||
}
|
||||
|
||||
@Operation(summary = "按成交日范围回补", description = "多天回补,内部按天切窗")
|
||||
@PostMapping("/bootstrap")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> bootstrap(
|
||||
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId,
|
||||
@Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
return ApiResponse.success("回补完成", pddOrderSyncService.bootstrapByConfirmRange(shopId, startDate, endDate));
|
||||
}
|
||||
|
||||
@Operation(summary = "增量同步", description = "调用 pdd.order.number.list.increment.get,按 updated_at 推进游标")
|
||||
@PostMapping("/incremental")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> incremental(
|
||||
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId) {
|
||||
return ApiResponse.success("增量同步完成", pddOrderSyncService.syncIncremental(shopId));
|
||||
}
|
||||
|
||||
@Operation(summary = "按订单号补拉", description = "调用 pdd.order.information.get")
|
||||
@PostMapping("/repair")
|
||||
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
|
||||
public ApiResponse<PddOrderSyncResultVO> repair(@Valid @RequestBody PddOrderRepairDTO dto) {
|
||||
return ApiResponse.success("补单完成", pddOrderSyncService.repair(dto));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.hook;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 外部订单落库后的扩展点。后续「外部订单转内部 ec_order」应实现本接口,勿塞进 upsert 主流程。
|
||||
*/
|
||||
public interface PddOrderAfterSyncListener {
|
||||
|
||||
/**
|
||||
* @param companyId 公司
|
||||
* @param shopId 内部店铺
|
||||
* @param pddOrderIds 本次 upsert 涉及的 ec_pdd_order.id
|
||||
* @param syncMode bootstrap | incremental | repair | day
|
||||
*/
|
||||
void onOrdersUpserted(Long companyId, Long shopId, List<Long> pddOrderIds, String syncMode);
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.job;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.service.PddOrderSyncService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 定时增量同步已绑定外部店的拼多多店铺;跳过增量游标 status=2(出错暂停)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@ConditionalOnProperty(prefix = "pdd.order-sync", name = "incremental-job-enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class PddOrderIncrementalSyncJob {
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final PlatformMapper platformMapper;
|
||||
private final PddOrderSyncCursorMapper cursorMapper;
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
|
||||
public PddOrderIncrementalSyncJob(ShopMapper shopMapper,
|
||||
PlatformMapper platformMapper,
|
||||
PddOrderSyncCursorMapper cursorMapper,
|
||||
PddOrderSyncService pddOrderSyncService) {
|
||||
this.shopMapper = shopMapper;
|
||||
this.platformMapper = platformMapper;
|
||||
this.cursorMapper = cursorMapper;
|
||||
this.pddOrderSyncService = pddOrderSyncService;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "${pdd.order-sync.incremental-cron:0 */5 * * * ?}")
|
||||
public void run() {
|
||||
List<PlatformPO> pddPlatforms = platformMapper.selectList(new LambdaQueryWrapper<PlatformPO>()
|
||||
.eq(PlatformPO::getPlatformCode, "pdd"));
|
||||
if (pddPlatforms.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> platformIds = pddPlatforms.stream().map(PlatformPO::getId).collect(Collectors.toSet());
|
||||
List<ShopPO> shops = shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
|
||||
.in(ShopPO::getPlatformId, platformIds)
|
||||
.isNotNull(ShopPO::getExternalShopId)
|
||||
.ne(ShopPO::getExternalShopId, ""));
|
||||
Set<Long> done = new HashSet<>();
|
||||
for (ShopPO shop : shops) {
|
||||
if (!done.add(shop.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (isIncrementalPaused(shop.getId())) {
|
||||
log.debug("跳过出错暂停的增量店铺 shopId={}", shop.getId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
pddOrderSyncService.syncIncrementalInternal(shop.getCompanyId(), shop.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("定时增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isIncrementalPaused(Long shopId) {
|
||||
PddOrderSyncCursorPO cursor = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
|
||||
.eq(PddOrderSyncCursorPO::getShopId, shopId)
|
||||
.eq(PddOrderSyncCursorPO::getSyncType, PddOrderSyncCursorPO.TYPE_INCREMENTAL)
|
||||
.last("LIMIT 1"));
|
||||
return cursor != null && Integer.valueOf(2).equals(cursor.getStatus());
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
|
||||
@Mapper
|
||||
public interface PddOrderSyncCursorMapper extends BaseMapper<PddOrderSyncCursorPO> {
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
|
||||
/**
|
||||
* 一次同步所需的店铺/授权上下文。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class PddOrderSyncShopContext {
|
||||
|
||||
private ShopPO internalShop;
|
||||
private PddShopPO pddShop;
|
||||
private PddAuthPO auth;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private Long mallId;
|
||||
private String accessToken;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "按订单号补拉拼多多订单")
|
||||
public class PddOrderRepairDTO {
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "内部店铺 ID", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private Long shopId;
|
||||
|
||||
@NotEmpty
|
||||
@Schema(description = "拼多多订单号列表", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private List<String> orderSns;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Schema(description = "按成交日同步拼多多订单")
|
||||
public class PddOrderSyncDayDTO {
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "内部店铺 ID", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private Long shopId;
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "成交日期(按天,东八区)", example = "2026-08-03", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private LocalDate confirmDate;
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_pdd_order_sync_cursor")
|
||||
public class PddOrderSyncCursorPO {
|
||||
|
||||
public static final String TYPE_BOOTSTRAP = "bootstrap";
|
||||
public static final String TYPE_INCREMENTAL = "incremental";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("pdd_auth_id")
|
||||
private Long pddAuthId;
|
||||
|
||||
@TableField("sync_type")
|
||||
private String syncType;
|
||||
|
||||
@TableField("last_cursor_at")
|
||||
private LocalDateTime lastCursorAt;
|
||||
|
||||
@TableField("overlap_seconds")
|
||||
private Integer overlapSeconds;
|
||||
|
||||
/** 0停用 1正常 2出错暂停 */
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField("last_success_time")
|
||||
private LocalDateTime lastSuccessTime;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@Schema(description = "拼多多订单同步结果")
|
||||
public class PddOrderSyncResultVO {
|
||||
|
||||
@Schema(description = "同步模式:day/bootstrap/incremental/repair")
|
||||
private String mode;
|
||||
|
||||
@Schema(description = "内部店铺 ID")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "拉取到的订单条数(含跳过)")
|
||||
private int fetchedCount;
|
||||
|
||||
@Schema(description = "实际 upsert 条数")
|
||||
private int upsertedCount;
|
||||
|
||||
@Schema(description = "跳过条数")
|
||||
private int skippedCount;
|
||||
|
||||
@Schema(description = "错误信息(若有)")
|
||||
@Builder.Default
|
||||
private List<String> errors = new ArrayList<>();
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper.PddAuthMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
@Service
|
||||
public class PddOrderSyncContextResolver {
|
||||
|
||||
private static final String PLATFORM_CODE_PDD = "pdd";
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopMapper shopMapper;
|
||||
private final PlatformMapper platformMapper;
|
||||
private final PddShopMapper pddShopMapper;
|
||||
private final PddAuthMapper pddAuthMapper;
|
||||
|
||||
public PddOrderSyncContextResolver(CurrentUserContext currentUserContext,
|
||||
ShopMapper shopMapper,
|
||||
PlatformMapper platformMapper,
|
||||
PddShopMapper pddShopMapper,
|
||||
PddAuthMapper pddAuthMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopMapper = shopMapper;
|
||||
this.platformMapper = platformMapper;
|
||||
this.pddShopMapper = pddShopMapper;
|
||||
this.pddAuthMapper = pddAuthMapper;
|
||||
}
|
||||
|
||||
public PddOrderSyncShopContext resolveForCurrentCompany(Long shopId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return resolve(companyId, shopId);
|
||||
}
|
||||
|
||||
public PddOrderSyncShopContext resolve(Long companyId, Long shopId) {
|
||||
if (shopId == null) {
|
||||
throw new BusinessException("店铺 ID 不能为空");
|
||||
}
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
throw new BusinessException("内部店铺不存在或不属于当前公司");
|
||||
}
|
||||
PlatformPO platform = platformMapper.selectById(shop.getPlatformId());
|
||||
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
|
||||
throw new BusinessException("仅支持拼多多平台店铺同步订单");
|
||||
}
|
||||
if (!StringUtils.hasText(shop.getExternalShopId())) {
|
||||
throw new BusinessException("店铺尚未绑定拼多多外部店,请先完成授权");
|
||||
}
|
||||
Long mallId;
|
||||
try {
|
||||
mallId = Long.parseLong(shop.getExternalShopId().trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("外部店铺 ID 非法: " + shop.getExternalShopId());
|
||||
}
|
||||
|
||||
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
|
||||
.eq(PddShopPO::getCompanyId, companyId)
|
||||
.eq(PddShopPO::getMallId, mallId)
|
||||
.last("LIMIT 1"));
|
||||
if (pddShop == null || pddShop.getPddAuthId() == null) {
|
||||
throw new BusinessException("未找到拼多多店铺授权绑定,请重新授权");
|
||||
}
|
||||
PddAuthPO auth = pddAuthMapper.selectById(pddShop.getPddAuthId());
|
||||
if (auth == null || auth.getStatus() == null || auth.getStatus() != 1
|
||||
|| !StringUtils.hasText(auth.getAccessToken())) {
|
||||
throw new BusinessException("拼多多授权无效或已失效,请重新授权");
|
||||
}
|
||||
|
||||
return PddOrderSyncShopContext.builder()
|
||||
.internalShop(shop)
|
||||
.pddShop(pddShop)
|
||||
.auth(auth)
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.mallId(mallId)
|
||||
.accessToken(auth.getAccessToken())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.config.PddOrderSyncProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopRateLimitedException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.order.PddOrderPopApiClient;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.hook.PddOrderAfterSyncListener;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto.PddOrderRepairDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.po.PddOrderSyncCursorPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.vo.PddOrderSyncResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 拼多多订单同步门面:day(按天回补)/ incremental / repair。
|
||||
* 只写 ec_pdd_*;转内部订单通过 {@link PddOrderAfterSyncListener}。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PddOrderSyncService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final String LOCK_PREFIX = "pdd:order:sync:lock:";
|
||||
|
||||
private final PddOrderSyncContextResolver contextResolver;
|
||||
private final PddOrderPopApiClient apiClient;
|
||||
private final PddOrderUpsertService upsertService;
|
||||
private final PddOrderSyncCursorMapper cursorMapper;
|
||||
private final PddOrderSyncProperties syncProperties;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ShopMapper shopMapper;
|
||||
private final List<PddOrderAfterSyncListener> afterSyncListeners;
|
||||
|
||||
public PddOrderSyncService(PddOrderSyncContextResolver contextResolver,
|
||||
PddOrderPopApiClient apiClient,
|
||||
PddOrderUpsertService upsertService,
|
||||
PddOrderSyncCursorMapper cursorMapper,
|
||||
PddOrderSyncProperties syncProperties,
|
||||
StringRedisTemplate stringRedisTemplate,
|
||||
ShopMapper shopMapper,
|
||||
List<PddOrderAfterSyncListener> afterSyncListeners) {
|
||||
this.contextResolver = contextResolver;
|
||||
this.apiClient = apiClient;
|
||||
this.upsertService = upsertService;
|
||||
this.cursorMapper = cursorMapper;
|
||||
this.syncProperties = syncProperties;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.shopMapper = shopMapper;
|
||||
this.afterSyncListeners = afterSyncListeners != null ? afterSyncListeners : List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按成交日同步一天(list.get,窗口 ≤24h)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncByConfirmDate(PddOrderSyncDayDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, dto.getConfirmDate(), dto.getConfirmDate(), "day"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按成交日起止回补(多天切 24h 窗)。
|
||||
*/
|
||||
public PddOrderSyncResultVO bootstrapByConfirmRange(Long shopId, LocalDate startDate, LocalDate endDate) {
|
||||
if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
|
||||
throw new BusinessException("回补日期范围无效");
|
||||
}
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, startDate, endDate, "bootstrap"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量:按 updated_at 从游标拉到现在(≤30min 切窗)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncIncremental(Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Job 用:按公司扫店(当前实现:对传入 shopId 做增量)。
|
||||
*/
|
||||
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
|
||||
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 order_sn 补单。
|
||||
*/
|
||||
public PddOrderSyncResultVO repair(PddOrderRepairDTO dto) {
|
||||
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
|
||||
return withShopLock(ctx.getShopId(), () -> {
|
||||
List<Long> upsertedIds = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
int fetched = 0;
|
||||
int upserted = 0;
|
||||
int skipped = 0;
|
||||
for (String orderSn : dto.getOrderSns()) {
|
||||
if (!StringUtils.hasText(orderSn)) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
PddOrderPopApiClient.RawOrder raw = apiClient.fetchOrderInformation(
|
||||
ctx.getMallId(), ctx.getAccessToken(), orderSn.trim());
|
||||
fetched++;
|
||||
if (raw == null || raw.snapshot() == null) {
|
||||
skipped++;
|
||||
errors.add(orderSn + ": 未返回订单");
|
||||
continue;
|
||||
}
|
||||
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), true);
|
||||
if (id != null) {
|
||||
upsertedIds.add(id);
|
||||
upserted++;
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
// 补单不推进、不改写 bootstrap/incremental 游标
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.warn("补单失败 orderSn={}: {}", orderSn, e.getMessage());
|
||||
errors.add(orderSn + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
notifyListeners(ctx, upsertedIds, "repair");
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("repair")
|
||||
.shopId(ctx.getShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(skipped)
|
||||
.errors(errors)
|
||||
.build();
|
||||
});
|
||||
}
|
||||
|
||||
public List<ShopPO> listBoundPddShops(Long companyId) {
|
||||
return shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.isNotNull(ShopPO::getExternalShopId)
|
||||
.ne(ShopPO::getExternalShopId, ""));
|
||||
}
|
||||
|
||||
private PddOrderSyncResultVO doSyncConfirmRange(PddOrderSyncShopContext ctx,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
String mode) {
|
||||
List<Long> upsertedIds = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
int fetched = 0;
|
||||
int upserted = 0;
|
||||
try {
|
||||
for (LocalDate day = startDate; !day.isAfter(endDate); day = day.plusDays(1)) {
|
||||
LocalDateTime dayStart = day.atStartOfDay();
|
||||
LocalDateTime dayEnd = day.plusDays(1).atStartOfDay().minusSeconds(1);
|
||||
long startTs = dayStart.atZone(ZONE).toEpochSecond();
|
||||
long endTs = dayEnd.atZone(ZONE).toEpochSecond();
|
||||
int page = 1;
|
||||
boolean hasNext = true;
|
||||
while (hasNext) {
|
||||
PddOrderPopApiClient.ListPage pageData = apiClient.fetchOrderListByConfirmAt(
|
||||
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
|
||||
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
|
||||
fetched++;
|
||||
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (id != null) {
|
||||
upsertedIds.add(id);
|
||||
upserted++;
|
||||
}
|
||||
}
|
||||
hasNext = pageData.hasNext();
|
||||
page++;
|
||||
}
|
||||
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, dayEnd);
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
} catch (BusinessException e) {
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("按成交日同步失败 shopId={}", ctx.getShopId(), e);
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
|
||||
throw new BusinessException("同步失败: " + e.getMessage());
|
||||
}
|
||||
notifyListeners(ctx, upsertedIds, mode);
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode(mode)
|
||||
.shopId(ctx.getShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(Math.max(fetched - upserted, 0))
|
||||
.errors(errors)
|
||||
.build();
|
||||
}
|
||||
|
||||
private PddOrderSyncResultVO doIncremental(PddOrderSyncShopContext ctx) {
|
||||
List<Long> upsertedIds = new ArrayList<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
int fetched = 0;
|
||||
int upserted = 0;
|
||||
int overlap = Math.max(syncProperties.getOverlapSeconds(), 0);
|
||||
LocalDateTime now = LocalDateTime.now(ZONE);
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL);
|
||||
LocalDateTime cursorAt = cursor.getLastCursorAt() != null
|
||||
? cursor.getLastCursorAt()
|
||||
: now.minusMinutes(30);
|
||||
LocalDateTime pullStart = cursorAt.minusSeconds(overlap);
|
||||
if (pullStart.isAfter(now)) {
|
||||
pullStart = now.minusMinutes(1);
|
||||
}
|
||||
|
||||
try {
|
||||
LocalDateTime windowStart = pullStart;
|
||||
while (windowStart.isBefore(now)) {
|
||||
LocalDateTime windowEnd = windowStart.plusMinutes(30);
|
||||
if (windowEnd.isAfter(now)) {
|
||||
windowEnd = now;
|
||||
}
|
||||
// 保证窗口不超过 30 分钟
|
||||
if (Duration.between(windowStart, windowEnd).toSeconds() > 30 * 60) {
|
||||
windowEnd = windowStart.plusMinutes(30).minusSeconds(1);
|
||||
}
|
||||
long startTs = windowStart.atZone(ZONE).toEpochSecond();
|
||||
long endTs = windowEnd.atZone(ZONE).toEpochSecond();
|
||||
if (endTs <= startTs) {
|
||||
endTs = startTs + 1;
|
||||
}
|
||||
|
||||
int page = 1;
|
||||
boolean hasNext = true;
|
||||
while (hasNext) {
|
||||
PddOrderPopApiClient.ListPage pageData = apiClient.fetchOrderListByUpdatedAt(
|
||||
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
|
||||
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
|
||||
fetched++;
|
||||
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (id != null) {
|
||||
upsertedIds.add(id);
|
||||
upserted++;
|
||||
}
|
||||
}
|
||||
hasNext = pageData.hasNext();
|
||||
page++;
|
||||
}
|
||||
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, windowEnd);
|
||||
windowStart = windowEnd;
|
||||
}
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
errors.add(e.getMessage());
|
||||
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
} catch (BusinessException e) {
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("增量同步失败 shopId={}", ctx.getShopId(), e);
|
||||
errors.add(e.getMessage());
|
||||
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
|
||||
throw new BusinessException("增量同步失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
notifyListeners(ctx, upsertedIds, "incremental");
|
||||
return PddOrderSyncResultVO.builder()
|
||||
.mode("incremental")
|
||||
.shopId(ctx.getShopId())
|
||||
.fetchedCount(fetched)
|
||||
.upsertedCount(upserted)
|
||||
.skippedCount(Math.max(fetched - upserted, 0))
|
||||
.errors(errors)
|
||||
.build();
|
||||
}
|
||||
|
||||
private PddOrderSyncCursorPO getOrCreateCursor(PddOrderSyncShopContext ctx, String syncType) {
|
||||
PddOrderSyncCursorPO existing = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
|
||||
.eq(PddOrderSyncCursorPO::getShopId, ctx.getShopId())
|
||||
.eq(PddOrderSyncCursorPO::getSyncType, syncType)
|
||||
.last("LIMIT 1"));
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
PddOrderSyncCursorPO cursor = new PddOrderSyncCursorPO();
|
||||
cursor.setCompanyId(ctx.getCompanyId());
|
||||
cursor.setShopId(ctx.getShopId());
|
||||
cursor.setPddAuthId(ctx.getAuth().getId());
|
||||
cursor.setSyncType(syncType);
|
||||
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
cursor.setStatus(1);
|
||||
cursorMapper.insert(cursor);
|
||||
return cursor;
|
||||
}
|
||||
|
||||
private void saveCursorSuccess(PddOrderSyncShopContext ctx, String syncType, LocalDateTime cursorAt) {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
cursor.setLastCursorAt(cursorAt);
|
||||
cursor.setStatus(1);
|
||||
cursor.setLastError(null);
|
||||
cursor.setLastSuccessTime(LocalDateTime.now(ZONE));
|
||||
cursor.setPddAuthId(ctx.getAuth().getId());
|
||||
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
|
||||
cursorMapper.updateById(cursor);
|
||||
}
|
||||
|
||||
/** 业务失败:游标 status=2,Job 将跳过直至人工恢复。 */
|
||||
private void markCursorError(PddOrderSyncShopContext ctx, String syncType, String error) {
|
||||
try {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
cursor.setStatus(2);
|
||||
cursor.setLastError(truncateError(error));
|
||||
cursorMapper.updateById(cursor);
|
||||
} catch (Exception e) {
|
||||
log.warn("写入同步游标错误失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 限流:只记 last_error,保持可调度(不置 status=2),不推进游标。 */
|
||||
private void noteRateLimit(PddOrderSyncShopContext ctx, String syncType, String error) {
|
||||
try {
|
||||
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
|
||||
if (cursor.getStatus() == null || cursor.getStatus() == 0) {
|
||||
cursor.setStatus(1);
|
||||
}
|
||||
cursor.setLastError(truncateError(error));
|
||||
cursorMapper.updateById(cursor);
|
||||
} catch (Exception e) {
|
||||
log.warn("写入限流备注失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static String truncateError(String error) {
|
||||
if (error == null) {
|
||||
return null;
|
||||
}
|
||||
return error.length() > 900 ? error.substring(0, 900) : error;
|
||||
}
|
||||
|
||||
private void notifyListeners(PddOrderSyncShopContext ctx, List<Long> ids, String mode) {
|
||||
if (ids == null || ids.isEmpty() || afterSyncListeners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (PddOrderAfterSyncListener listener : afterSyncListeners) {
|
||||
try {
|
||||
listener.onOrdersUpserted(ctx.getCompanyId(), ctx.getShopId(), ids, mode);
|
||||
} catch (Exception e) {
|
||||
log.warn("PddOrderAfterSyncListener 执行失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T withShopLock(Long shopId, SyncAction<T> action) {
|
||||
String token = UUID.randomUUID().toString();
|
||||
String key = LOCK_PREFIX + shopId;
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key, token, Duration.ofSeconds(Math.max(syncProperties.getLockTtlSeconds(), 60)));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
throw new BusinessException("该店铺正在同步中,请稍后重试");
|
||||
}
|
||||
try {
|
||||
return action.run();
|
||||
} finally {
|
||||
String current = stringRedisTemplate.opsForValue().get(key);
|
||||
if (token.equals(current)) {
|
||||
stringRedisTemplate.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface SyncAction<T> {
|
||||
T run();
|
||||
}
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.mapper.PddOrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.mapper.PddOrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.model.po.PddOrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.model.po.PddOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.order.PddOrderApiSnapshot;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.model.PddOrderSyncShopContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 将平台订单快照幂等写入 ec_pdd_order / ec_pdd_order_item。
|
||||
* 仅负责外部镜像落库;转内部订单通过 {@link top.xyquan.ecomdmbbackend.modules.ecom.pdd.order.sync.hook.PddOrderAfterSyncListener}。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PddOrderUpsertService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter[] TIME_FORMATTERS = new DateTimeFormatter[]{
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
|
||||
DateTimeFormatter.ISO_LOCAL_DATE_TIME
|
||||
};
|
||||
|
||||
private final PddOrderMapper pddOrderMapper;
|
||||
private final PddOrderItemMapper pddOrderItemMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PddOrderUpsertService(PddOrderMapper pddOrderMapper,
|
||||
PddOrderItemMapper pddOrderItemMapper,
|
||||
ObjectMapper objectMapper) {
|
||||
this.pddOrderMapper = pddOrderMapper;
|
||||
this.pddOrderItemMapper = pddOrderItemMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long upsert(PddOrderSyncShopContext ctx, PddOrderApiSnapshot snapshot, Object rawSdkObject, boolean force) {
|
||||
if (snapshot == null || !StringUtils.hasText(snapshot.getOrderSn())) {
|
||||
return null;
|
||||
}
|
||||
LocalDateTime remoteUpdated = parseTime(snapshot.getUpdatedAt());
|
||||
PddOrderPO existing = pddOrderMapper.selectOne(new LambdaQueryWrapper<PddOrderPO>()
|
||||
.eq(PddOrderPO::getCompanyId, ctx.getCompanyId())
|
||||
.eq(PddOrderPO::getOrderSn, snapshot.getOrderSn())
|
||||
.last("LIMIT 1"));
|
||||
|
||||
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
|
||||
&& !existing.getPddUpdatedAt().isBefore(remoteUpdated)) {
|
||||
return existing.getId();
|
||||
}
|
||||
|
||||
PddOrderPO order = existing != null ? existing : new PddOrderPO();
|
||||
order.setCompanyId(ctx.getCompanyId());
|
||||
order.setShopId(ctx.getShopId());
|
||||
order.setPddAuthId(ctx.getAuth().getId());
|
||||
order.setOrderSn(snapshot.getOrderSn());
|
||||
order.setOrderStatus(snapshot.getOrderStatus() != null ? snapshot.getOrderStatus() : 0);
|
||||
order.setRefundStatus(snapshot.getRefundStatus());
|
||||
order.setAfterSalesStatus(snapshot.getAfterSalesStatus());
|
||||
order.setConfirmStatus(snapshot.getConfirmStatus());
|
||||
order.setPayAmount(toMoney(snapshot.getPayAmount()));
|
||||
order.setGoodsAmount(toMoney(snapshot.getGoodsAmount()));
|
||||
order.setDiscountAmount(toMoney(snapshot.getDiscountAmount()));
|
||||
order.setPostage(toMoney(snapshot.getPostage()));
|
||||
order.setPlatformDiscount(toMoney(snapshot.getPlatformDiscount()));
|
||||
order.setSellerDiscount(toMoney(snapshot.getSellerDiscount()));
|
||||
order.setLogisticsId(snapshot.getLogisticsId());
|
||||
order.setTrackingNumber(snapshot.getTrackingNumber());
|
||||
order.setCreatedTime(firstNonNull(parseTime(snapshot.getCreatedTime()), LocalDateTime.now(ZONE)));
|
||||
order.setPayTime(parseTime(snapshot.getPayTime()));
|
||||
order.setConfirmTime(parseTime(snapshot.getConfirmTime()));
|
||||
order.setShippingTime(parseTime(snapshot.getShippingTime()));
|
||||
order.setReceiveTime(parseTime(snapshot.getReceiveTime()));
|
||||
order.setLastShipTime(parseTime(snapshot.getLastShipTime()));
|
||||
order.setPddUpdatedAt(remoteUpdated);
|
||||
order.setProvince(snapshot.getProvince());
|
||||
order.setCity(snapshot.getCity());
|
||||
order.setTown(snapshot.getTown());
|
||||
order.setReceiverNameMask(snapshot.getReceiverNameMask());
|
||||
order.setReceiverPhoneMask(snapshot.getReceiverPhoneMask());
|
||||
order.setReceiverAddressMask(snapshot.getReceiverAddressMask());
|
||||
order.setBuyerMemo(snapshot.getBuyerMemo());
|
||||
order.setRemark(snapshot.getRemark());
|
||||
order.setTradeType(snapshot.getTradeType());
|
||||
order.setIsPreSale(snapshot.getIsPreSale());
|
||||
order.setGroupStatus(snapshot.getGroupStatus());
|
||||
order.setRawResponse(writeJson(rawSdkObject != null ? rawSdkObject : snapshot));
|
||||
order.setLastSyncTime(LocalDateTime.now(ZONE));
|
||||
|
||||
if (existing == null) {
|
||||
pddOrderMapper.insert(order);
|
||||
} else {
|
||||
pddOrderMapper.updateById(order);
|
||||
}
|
||||
|
||||
replaceItems(order, snapshot);
|
||||
return order.getId();
|
||||
}
|
||||
|
||||
private void replaceItems(PddOrderPO order, PddOrderApiSnapshot snapshot) {
|
||||
pddOrderItemMapper.delete(new LambdaQueryWrapper<PddOrderItemPO>()
|
||||
.eq(PddOrderItemPO::getOrderId, order.getId()));
|
||||
if (snapshot.getItemList() == null || snapshot.getItemList().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<PddOrderItemPO> rows = new ArrayList<>();
|
||||
for (PddOrderApiSnapshot.Item item : snapshot.getItemList()) {
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
PddOrderItemPO row = new PddOrderItemPO();
|
||||
row.setOrderId(order.getId());
|
||||
row.setCompanyId(order.getCompanyId());
|
||||
row.setOrderSn(order.getOrderSn());
|
||||
row.setGoodsId(StringUtils.hasText(item.getGoodsId()) ? item.getGoodsId() : "0");
|
||||
row.setSkuId(StringUtils.hasText(item.getSkuId()) ? item.getSkuId() : "0");
|
||||
row.setGoodsName(StringUtils.hasText(item.getGoodsName()) ? item.getGoodsName() : "-");
|
||||
row.setGoodsSpec(item.getGoodsSpec());
|
||||
row.setGoodsImg(item.getGoodsImg());
|
||||
row.setGoodsCount(item.getGoodsCount() != null ? item.getGoodsCount() : 1);
|
||||
row.setGoodsPrice(toMoney(item.getGoodsPrice()));
|
||||
row.setOuterGoodsId(item.getOuterGoodsId());
|
||||
row.setOuterId(item.getOuterId());
|
||||
rows.add(row);
|
||||
pddOrderItemMapper.insert(row);
|
||||
}
|
||||
}
|
||||
|
||||
private String writeJson(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.warn("序列化订单 raw_response 失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static BigDecimal toMoney(Double value) {
|
||||
if (value == null) {
|
||||
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static LocalDateTime parseTime(String text) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return null;
|
||||
}
|
||||
String t = text.trim();
|
||||
for (DateTimeFormatter formatter : TIME_FORMATTERS) {
|
||||
try {
|
||||
return LocalDateTime.parse(t, formatter);
|
||||
} catch (DateTimeParseException ignored) {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.ofInstant(java.time.Instant.ofEpochSecond(Long.parseLong(t)), ZONE);
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
private static <T> T firstNonNull(T... values) {
|
||||
if (values == null) {
|
||||
return null;
|
||||
}
|
||||
for (T v : values) {
|
||||
if (v != null) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop;
|
||||
|
||||
/**
|
||||
* 拼多多 POP API type 常量(限流配置 key / 日志 / Client 共用)。
|
||||
*/
|
||||
public final class PddPopApiTypes {
|
||||
|
||||
private PddPopApiTypes() {
|
||||
}
|
||||
|
||||
// ---------- 订单 ----------
|
||||
public static final String ORDER_LIST_GET = "pdd.order.list.get";
|
||||
public static final String ORDER_INCREMENT_GET = "pdd.order.number.list.increment.get";
|
||||
public static final String ORDER_INFORMATION_GET = "pdd.order.information.get";
|
||||
|
||||
// ---------- 店铺 ----------
|
||||
public static final String MALL_INFO_GET = "pdd.mall.info.get";
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop;
|
||||
|
||||
import com.pdd.pop.sdk.http.PopAccessTokenClient;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
|
||||
|
||||
/**
|
||||
* 拼多多 POP SDK 客户端工厂。
|
||||
* <ul>
|
||||
* <li>HTTP 客户端全局复用(线程安全的出站通道)</li>
|
||||
* <li>AccessToken 客户端仍按次创建(短生命周期,用完 destroy)</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class PddPopClientFactory {
|
||||
|
||||
private final PddOAuthProperties properties;
|
||||
private final Object httpClientLock = new Object();
|
||||
private volatile PopHttpClient sharedHttpClient;
|
||||
|
||||
public PddPopClientFactory(PddOAuthProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/** 创建 AccessToken 换票客户端(用完请 destroy)。 */
|
||||
public PopAccessTokenClient createAccessTokenClient() {
|
||||
assertConfigured();
|
||||
return new PopAccessTokenClient(properties.getClientId(), properties.getClientSecret());
|
||||
}
|
||||
|
||||
/** 获取复用的 POP HTTP 客户端。 */
|
||||
public PopClient getHttpClient() {
|
||||
assertConfigured();
|
||||
PopHttpClient client = sharedHttpClient;
|
||||
if (client == null) {
|
||||
synchronized (httpClientLock) {
|
||||
client = sharedHttpClient;
|
||||
if (client == null) {
|
||||
sharedHttpClient = new PopHttpClient(properties.getClientId(), properties.getClientSecret());
|
||||
client = sharedHttpClient;
|
||||
log.info("初始化复用 PopHttpClient clientId={}", properties.getClientId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
synchronized (httpClientLock) {
|
||||
if (sharedHttpClient != null) {
|
||||
try {
|
||||
sharedHttpClient.destroy();
|
||||
} catch (Exception e) {
|
||||
log.warn("销毁 PopHttpClient 失败: {}", e.getMessage());
|
||||
} finally {
|
||||
sharedHttpClient = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void assertConfigured() {
|
||||
if (!StringUtils.hasText(properties.getClientId())
|
||||
|| !StringUtils.hasText(properties.getClientSecret())) {
|
||||
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
|
||||
/**
|
||||
* POP 主动限流等待超时,或平台返回频控错误。
|
||||
*/
|
||||
public class PddPopRateLimitedException extends BusinessException {
|
||||
|
||||
public PddPopRateLimitedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopApiTypes;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 拼多多 POP 出站公共配置:默认分页与按接口限流。
|
||||
* <p>限流规则 key 使用 {@link PddPopApiTypes} 中的 API type。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "pdd.pop")
|
||||
public class PddPopProperties {
|
||||
|
||||
/** 列表类接口默认分页大小(最大 100) */
|
||||
private int defaultPageSize = 100;
|
||||
|
||||
private RateLimit rateLimit = new RateLimit();
|
||||
|
||||
@Data
|
||||
public static class RateLimit {
|
||||
/** 是否启用主动限流;关闭仅用于本地调试 */
|
||||
private boolean enabled = true;
|
||||
|
||||
/** 获取令牌最长等待毫秒 */
|
||||
private long acquireWaitMs = 5000;
|
||||
|
||||
/**
|
||||
* 平台频控被动退避毫秒序列;用尽仍失败则抛出限流异常。
|
||||
* 默认 2s → 5s → 15s(共最多 3 次退避,合计至多 4 次尝试)。
|
||||
*/
|
||||
private List<Long> backoffMs = List.of(2000L, 5000L, 15000L);
|
||||
|
||||
/** 按 API type 配置限流;缺省回落 defaultRule */
|
||||
private Map<String, ApiRule> apis = defaultApis();
|
||||
|
||||
/**
|
||||
* 官方 FAQ:商家限流=单店铺,接口总限流=全平台。
|
||||
* 默认取官方示例上限约 60% 单店余量 + 本 ISV 短窗保守值。
|
||||
*/
|
||||
private ApiRule defaultRule = ApiRule.of(6000, 60, 800, 10);
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ApiRule {
|
||||
/** 单店铺窗口内上限(商家限流) */
|
||||
private int shopLimit = 6000;
|
||||
/** 单店铺窗口秒数 */
|
||||
private int shopWindowSeconds = 60;
|
||||
/** 本 ISV 合计短窗上限(对冲接口总限流) */
|
||||
private int appBurstLimit = 800;
|
||||
/** 本 ISV 短窗秒数 */
|
||||
private int appBurstWindowSeconds = 10;
|
||||
|
||||
public static ApiRule of(int shopLimit, int shopWindowSeconds, int appBurstLimit, int appBurstWindowSeconds) {
|
||||
ApiRule rule = new ApiRule();
|
||||
rule.setShopLimit(shopLimit);
|
||||
rule.setShopWindowSeconds(shopWindowSeconds);
|
||||
rule.setAppBurstLimit(appBurstLimit);
|
||||
rule.setAppBurstWindowSeconds(appBurstWindowSeconds);
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析指定 API 的限流规则。 */
|
||||
public ApiRule resolveRule(String apiType) {
|
||||
if (apiType != null && rateLimit.getApis() != null && rateLimit.getApis().containsKey(apiType)) {
|
||||
return rateLimit.getApis().get(apiType);
|
||||
}
|
||||
return rateLimit.getDefaultRule();
|
||||
}
|
||||
|
||||
private static Map<String, ApiRule> defaultApis() {
|
||||
Map<String, ApiRule> map = new LinkedHashMap<>();
|
||||
ApiRule orderLike = ApiRule.of(6000, 60, 800, 10);
|
||||
map.put(PddPopApiTypes.ORDER_LIST_GET, orderLike);
|
||||
map.put(PddPopApiTypes.ORDER_INCREMENT_GET, ApiRule.of(6000, 60, 800, 10));
|
||||
map.put(PddPopApiTypes.ORDER_INFORMATION_GET, ApiRule.of(6000, 60, 800, 10));
|
||||
map.put(PddPopApiTypes.MALL_INFO_GET, ApiRule.of(6000, 60, 800, 10));
|
||||
return map;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.mall;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 店铺信息防腐快照(pdd.mall.info.get),业务层勿依赖 SDK 响应类型。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class PddMallApiSnapshot {
|
||||
|
||||
private Long mallId;
|
||||
private String mallName;
|
||||
private String logo;
|
||||
private String mallDesc;
|
||||
private Integer merchantType;
|
||||
private Integer mallCharacter;
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.mall;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddMallInfoGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopApiTypes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopRateLimitedException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.support.PddPopInvokeSupport;
|
||||
|
||||
/**
|
||||
* 店铺域 POP 出站客户端({@value PddPopApiTypes#MALL_INFO_GET})。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class PddMallPopApiClient {
|
||||
|
||||
private final PddPopInvokeSupport invokeSupport;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PddMallPopApiClient(PddPopInvokeSupport invokeSupport, ObjectMapper objectMapper) {
|
||||
this.invokeSupport = invokeSupport;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取当前 accessToken 对应店铺信息。
|
||||
*
|
||||
* @param mallId 用于单店限流的 mall_id(授权回调可用 owner_id 解析值)
|
||||
* @param accessToken 店铺授权 token
|
||||
*/
|
||||
public PddMallApiSnapshot getMallInfo(Long mallId, String accessToken) throws Exception {
|
||||
return invokeSupport.invoke(PddPopApiTypes.MALL_INFO_GET, mallId, client -> {
|
||||
PddMallInfoGetResponse response = client.syncInvoke(new PddMallInfoGetRequest(), accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.MALL_INFO_GET);
|
||||
if (response.getMallInfoGetResponse() == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(response.getMallInfoGetResponse(), PddMallApiSnapshot.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 软失败版本:业务/网络异常返回 null(限流异常仍向上抛,避免静默打穿频控)。
|
||||
*/
|
||||
public PddMallApiSnapshot getMallInfoOrNull(Long mallId, String accessToken) {
|
||||
try {
|
||||
return getMallInfo(mallId, accessToken);
|
||||
} catch (Exception e) {
|
||||
// PddPopRateLimitedException 继承 RuntimeException,会被 Exception 捕获,需显式再抛
|
||||
if (e instanceof PddPopRateLimitedException) {
|
||||
throw (PddPopRateLimitedException) e;
|
||||
}
|
||||
log.warn("pdd.mall.info.get 失败 mallId={}: {}", mallId, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.order;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单 POP 防腐快照:三接口响应统一映射到此模型,业务侧不直接依赖 SDK 类型。
|
||||
* <p>SDK 字段远多于快照,未知属性一律忽略(如 address、country 等)。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class PddOrderApiSnapshot {
|
||||
|
||||
private String orderSn;
|
||||
private Integer orderStatus;
|
||||
private Integer refundStatus;
|
||||
private Integer afterSalesStatus;
|
||||
private Integer confirmStatus;
|
||||
private Double payAmount;
|
||||
private Double goodsAmount;
|
||||
private Double discountAmount;
|
||||
private Double postage;
|
||||
private Double platformDiscount;
|
||||
private Double sellerDiscount;
|
||||
private Long logisticsId;
|
||||
private String trackingNumber;
|
||||
private String createdTime;
|
||||
private String payTime;
|
||||
private String confirmTime;
|
||||
private String shippingTime;
|
||||
private String receiveTime;
|
||||
private String lastShipTime;
|
||||
private String updatedAt;
|
||||
private String province;
|
||||
private String city;
|
||||
private String town;
|
||||
private String receiverNameMask;
|
||||
private String receiverPhoneMask;
|
||||
private String receiverAddressMask;
|
||||
private String buyerMemo;
|
||||
private String remark;
|
||||
private Integer tradeType;
|
||||
private Integer isPreSale;
|
||||
private Integer groupStatus;
|
||||
private List<Item> itemList;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Item {
|
||||
private String goodsId;
|
||||
private String skuId;
|
||||
private String goodsName;
|
||||
private String goodsSpec;
|
||||
private String goodsImg;
|
||||
private Integer goodsCount;
|
||||
private Double goodsPrice;
|
||||
private String outerGoodsId;
|
||||
private String outerId;
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.order;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddOrderInformationGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddOrderListGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddOrderNumberListIncrementGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddOrderInformationGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddOrderListGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddOrderNumberListIncrementGetResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopApiTypes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.config.PddPopProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.support.PddPopInvokeSupport;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单域 POP 出站客户端:限流/退避交给 {@link PddPopInvokeSupport},结果映射为 {@link PddOrderApiSnapshot}。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class PddOrderPopApiClient {
|
||||
|
||||
private final PddPopInvokeSupport invokeSupport;
|
||||
private final PddPopProperties popProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PddOrderPopApiClient(PddPopInvokeSupport invokeSupport,
|
||||
PddPopProperties popProperties,
|
||||
ObjectMapper objectMapper) {
|
||||
this.invokeSupport = invokeSupport;
|
||||
this.popProperties = popProperties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** 按成交时间拉取订单列表({@value PddPopApiTypes#ORDER_LIST_GET})。 */
|
||||
public ListPage fetchOrderListByConfirmAt(Long mallId, String accessToken,
|
||||
long startConfirmAt, long endConfirmAt, int page) throws Exception {
|
||||
return invokeSupport.invoke(PddPopApiTypes.ORDER_LIST_GET, mallId, client -> {
|
||||
PddOrderListGetRequest request = new PddOrderListGetRequest();
|
||||
request.setStartConfirmAt(startConfirmAt);
|
||||
request.setEndConfirmAt(endConfirmAt);
|
||||
request.setOrderStatus(5);
|
||||
request.setRefundStatus(5);
|
||||
request.setPage(page);
|
||||
request.setPageSize(Math.min(popProperties.getDefaultPageSize(), 100));
|
||||
request.setUseHasNext(true);
|
||||
PddOrderListGetResponse response = client.syncInvoke(request, accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.ORDER_LIST_GET);
|
||||
|
||||
PddOrderListGetResponse.OrderListGetResponse body = response.getOrderListGetResponse();
|
||||
if (body == null || body.getOrderList() == null) {
|
||||
return ListPage.empty();
|
||||
}
|
||||
List<RawOrder> orders = new ArrayList<>();
|
||||
for (Object item : body.getOrderList()) {
|
||||
orders.add(toRaw(item));
|
||||
}
|
||||
return new ListPage(orders, Boolean.TRUE.equals(body.getHasNext()));
|
||||
});
|
||||
}
|
||||
|
||||
/** 按更新时间拉取增量订单列表({@value PddPopApiTypes#ORDER_INCREMENT_GET})。 */
|
||||
public ListPage fetchOrderListByUpdatedAt(Long mallId, String accessToken,
|
||||
long startUpdatedAt, long endUpdatedAt, int page) throws Exception {
|
||||
return invokeSupport.invoke(PddPopApiTypes.ORDER_INCREMENT_GET, mallId, client -> {
|
||||
PddOrderNumberListIncrementGetRequest request = new PddOrderNumberListIncrementGetRequest();
|
||||
request.setStartUpdatedAt(startUpdatedAt);
|
||||
request.setEndUpdatedAt(endUpdatedAt);
|
||||
request.setOrderStatus(5);
|
||||
request.setRefundStatus(5);
|
||||
request.setIsLuckyFlag(0);
|
||||
request.setPage(page);
|
||||
request.setPageSize(Math.min(popProperties.getDefaultPageSize(), 100));
|
||||
request.setUseHasNext(true);
|
||||
PddOrderNumberListIncrementGetResponse response = client.syncInvoke(request, accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.ORDER_INCREMENT_GET);
|
||||
|
||||
PddOrderNumberListIncrementGetResponse.OrderSnIncrementGetResponse body = response.getOrderSnIncrementGetResponse();
|
||||
if (body == null || body.getOrderSnList() == null) {
|
||||
return ListPage.empty();
|
||||
}
|
||||
List<RawOrder> orders = new ArrayList<>();
|
||||
for (Object item : body.getOrderSnList()) {
|
||||
orders.add(toRaw(item));
|
||||
}
|
||||
return new ListPage(orders, Boolean.TRUE.equals(body.getHasNext()));
|
||||
});
|
||||
}
|
||||
|
||||
/** 按订单号拉取单笔详情({@value PddPopApiTypes#ORDER_INFORMATION_GET})。 */
|
||||
public RawOrder fetchOrderInformation(Long mallId, String accessToken, String orderSn) throws Exception {
|
||||
return invokeSupport.invoke(PddPopApiTypes.ORDER_INFORMATION_GET, mallId, client -> {
|
||||
PddOrderInformationGetRequest request = new PddOrderInformationGetRequest();
|
||||
request.setOrderSn(orderSn);
|
||||
PddOrderInformationGetResponse response = client.syncInvoke(request, accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.ORDER_INFORMATION_GET);
|
||||
|
||||
if (response.getOrderInfoGetResponse() == null
|
||||
|| response.getOrderInfoGetResponse().getOrderInfo() == null) {
|
||||
return null;
|
||||
}
|
||||
return toRaw(response.getOrderInfoGetResponse().getOrderInfo());
|
||||
});
|
||||
}
|
||||
|
||||
private RawOrder toRaw(Object sdkItem) {
|
||||
PddOrderApiSnapshot snapshot = objectMapper.convertValue(sdkItem, PddOrderApiSnapshot.class);
|
||||
return new RawOrder(snapshot, sdkItem);
|
||||
}
|
||||
|
||||
/** 单笔订单:防腐快照 + 原始 SDK 对象(用于 raw_response)。 */
|
||||
public record RawOrder(PddOrderApiSnapshot snapshot, Object raw) {
|
||||
}
|
||||
|
||||
/** 列表分页结果。 */
|
||||
public record ListPage(List<RawOrder> orders, boolean hasNext) {
|
||||
static ListPage empty() {
|
||||
return new ListPage(Collections.emptyList(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.ratelimit;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopRateLimitedException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.config.PddPopProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* POP 出站限流:单店铺桶(商家限流)+ 本 ISV 短窗桶(对冲接口总限流)。
|
||||
* 双桶采用「先扣后补」:一侧失败则回滚另一侧已扣配额。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class PddPopRateLimiter {
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final PddPopProperties popProperties;
|
||||
private final PddOAuthProperties oauthProperties;
|
||||
|
||||
public PddPopRateLimiter(StringRedisTemplate stringRedisTemplate,
|
||||
PddPopProperties popProperties,
|
||||
PddOAuthProperties oauthProperties) {
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.popProperties = popProperties;
|
||||
this.oauthProperties = oauthProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 阻塞获取调用许可;超时抛 {@link PddPopRateLimitedException}。
|
||||
*
|
||||
* @param apiType 如 pdd.order.list.get
|
||||
* @param mallId 拼多多店铺 mall_id
|
||||
*/
|
||||
public void acquire(String apiType, Long mallId) {
|
||||
if (!popProperties.getRateLimit().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (mallId == null) {
|
||||
throw new BusinessException("限流需要 mallId");
|
||||
}
|
||||
PddPopProperties.ApiRule rule = popProperties.resolveRule(apiType);
|
||||
long deadline = System.currentTimeMillis() + popProperties.getRateLimit().getAcquireWaitMs();
|
||||
String clientId = oauthProperties.getClientId() == null ? "unknown" : oauthProperties.getClientId();
|
||||
String shopKey = shopKey(mallId, apiType, rule.getShopWindowSeconds());
|
||||
String appKey = appKey(clientId, apiType, rule.getAppBurstWindowSeconds());
|
||||
|
||||
while (true) {
|
||||
if (tryAcquireBoth(shopKey, rule.getShopLimit(), rule.getShopWindowSeconds(),
|
||||
appKey, rule.getAppBurstLimit(), rule.getAppBurstWindowSeconds())) {
|
||||
return;
|
||||
}
|
||||
if (System.currentTimeMillis() >= deadline) {
|
||||
throw new PddPopRateLimitedException(
|
||||
"拼多多接口调用过于频繁,请稍后重试(api=" + apiType + ", mallId=" + mallId + ")");
|
||||
}
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("等待限流许可被中断");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同时占用店铺桶与 ISV 桶;任一侧超限则回滚已成功的一侧。
|
||||
*/
|
||||
private boolean tryAcquireBoth(String shopKey, int shopLimit, int shopWindowSeconds,
|
||||
String appKey, int appLimit, int appWindowSeconds) {
|
||||
boolean shopOk = tryConsume(shopKey, shopLimit, shopWindowSeconds);
|
||||
if (!shopOk) {
|
||||
return false;
|
||||
}
|
||||
boolean appOk = tryConsume(appKey, appLimit, appWindowSeconds);
|
||||
if (!appOk) {
|
||||
rollback(shopKey);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean tryConsume(String key, int limit, int windowSeconds) {
|
||||
Long count = stringRedisTemplate.opsForValue().increment(key);
|
||||
if (count == null) {
|
||||
return false;
|
||||
}
|
||||
if (count == 1L) {
|
||||
stringRedisTemplate.expire(key, Duration.ofSeconds(Math.max(windowSeconds, 1) + 1L));
|
||||
}
|
||||
if (count <= limit) {
|
||||
return true;
|
||||
}
|
||||
rollback(key);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void rollback(String key) {
|
||||
try {
|
||||
Long after = stringRedisTemplate.opsForValue().decrement(key);
|
||||
if (after != null && after <= 0) {
|
||||
stringRedisTemplate.delete(key);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("限流配额回滚失败 key={}: {}", key, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static String shopKey(Long mallId, String apiType, int windowSeconds) {
|
||||
long bucket = System.currentTimeMillis() / 1000L / Math.max(windowSeconds, 1);
|
||||
return "pdd:pop:rl:shop:" + mallId + ":" + apiType + ":" + bucket;
|
||||
}
|
||||
|
||||
private static String appKey(String clientId, String apiType, int windowSeconds) {
|
||||
long bucket = System.currentTimeMillis() / 1000L / Math.max(windowSeconds, 1);
|
||||
return "pdd:pop:rl:app:" + clientId + ":" + apiType + ":" + bucket;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.support;
|
||||
|
||||
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopClientFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.PddPopRateLimitedException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.config.PddPopProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.pop.ratelimit.PddPopRateLimiter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* POP 出站公共能力:主动限流 + 平台频控退避 + 错误识别。
|
||||
* 各域 Client(order / mall / …)应通过本类发起调用,避免重复造轮子。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class PddPopInvokeSupport {
|
||||
|
||||
private final PddPopClientFactory popClientFactory;
|
||||
private final PddPopRateLimiter rateLimiter;
|
||||
private final PddPopProperties popProperties;
|
||||
|
||||
public PddPopInvokeSupport(PddPopClientFactory popClientFactory,
|
||||
PddPopRateLimiter rateLimiter,
|
||||
PddPopProperties popProperties) {
|
||||
this.popClientFactory = popClientFactory;
|
||||
this.rateLimiter = rateLimiter;
|
||||
this.popProperties = popProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 先申请限流许可,再调用;遇平台频控按配置退避重试。
|
||||
*/
|
||||
public <T> T invoke(String apiType, Long mallId, PopInvoker<T> invoker) throws Exception {
|
||||
List<Long> backoffMs = popProperties.getRateLimit().getBackoffMs();
|
||||
if (backoffMs == null) {
|
||||
backoffMs = List.of();
|
||||
}
|
||||
int maxAttempts = backoffMs.size() + 1;
|
||||
PddPopRateLimitedException last = null;
|
||||
for (int attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
rateLimiter.acquire(apiType, mallId);
|
||||
try {
|
||||
PopClient client = popClientFactory.getHttpClient();
|
||||
return invoker.invoke(client);
|
||||
} catch (PddPopRateLimitedException e) {
|
||||
last = e;
|
||||
if (attempt >= maxAttempts - 1) {
|
||||
throw e;
|
||||
}
|
||||
long sleepMs = Math.max(0L, backoffMs.get(attempt));
|
||||
log.warn("平台限流退避 api={} mallId={} attempt={} sleepMs={} msg={}",
|
||||
apiType, mallId, attempt + 1, sleepMs, e.getMessage());
|
||||
sleepQuietly(sleepMs);
|
||||
}
|
||||
}
|
||||
throw last != null ? last : new PddPopRateLimitedException(apiType + " 限流重试失败");
|
||||
}
|
||||
|
||||
/** 校验 POP 响应;频控抛 {@link PddPopRateLimitedException},其它业务错误抛 {@link BusinessException}。 */
|
||||
public void assertNoError(PopBaseHttpResponse response, String apiType) {
|
||||
if (response == null) {
|
||||
throw new BusinessException("拼多多接口无响应: " + apiType);
|
||||
}
|
||||
if (response.getErrorResponse() != null) {
|
||||
String msg = response.getErrorResponse().getErrorMsg();
|
||||
String code = String.valueOf(response.getErrorResponse().getErrorCode());
|
||||
if (isRateLimitMessage(msg, code)) {
|
||||
throw new PddPopRateLimitedException(apiType + " 触发平台限流: " + msg);
|
||||
}
|
||||
throw new BusinessException(apiType + " 调用失败: " + (StringUtils.hasText(msg) ? msg : code));
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRateLimitMessage(String msg, String code) {
|
||||
String m = (msg == null ? "" : msg) + " " + (code == null ? "" : code);
|
||||
String lower = m.toLowerCase();
|
||||
return lower.contains("limit") || lower.contains("freq")
|
||||
|| m.contains("限流") || m.contains("频率") || m.contains("过于频繁");
|
||||
}
|
||||
|
||||
private static void sleepQuietly(long ms) {
|
||||
if (ms <= 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("限流退避被中断");
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface PopInvoker<T> {
|
||||
T invoke(PopClient client) throws Exception;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user