fix: 修复并行导入两大bug — 死锁+FK外键;修复订单时间字段名order_date→order_time;修复successCount双重累加

This commit is contained in:
小蟑螂
2026-04-16 12:47:05 +08:00
parent 0a27d4ab57
commit 3ce5eba22e
3 changed files with 618 additions and 326 deletions
@@ -7,11 +7,17 @@ import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationP
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* 导入运行时上下文(贯穿整个导入过程) * 导入运行时上下文(贯穿整个导入过程)
* <p> * <p>
* 所有共享类型(内部类/枚举)也定义在此文件,避免循环依赖。 * 所有共享类型(内部类/枚举)也定义在此文件,避免循环依赖。
* <p>
* 线程安全:并行导入时,多个 Worker 线程并发读写集合,
* 故缓存Map/Set使用 ConcurrentHashMap / ConcurrentHashMap.newKeySet(),
* pendingOrders 使用 CopyOnWriteArrayList(写时复制,并行添加,flush时整体替换)。
*/ */
public class ImportRuntimeContext { public class ImportRuntimeContext {
@@ -123,37 +129,49 @@ public class ImportRuntimeContext {
public StringBuilder errorMessages = new StringBuilder(); public StringBuilder errorMessages = new StringBuilder();
} }
// ==================== 上下文字段 ==================== // ==================== 上下文字段(线程安全) ====================
private final Long companyId; private final Long companyId;
private final Long shopId; private final Long shopId;
private final Long createBy; private final Long createBy;
private final Long taskId;
private DateTimeFormatPattern detectedDatePattern; private DateTimeFormatPattern detectedDatePattern;
final Map<String, ProductSpecPO> specByCodeCache = new HashMap<>(); // 缓存:只读(预加载后不再写入),使用 ConcurrentHashMap 确保 workers 并行读取安全
final Map<String, ProductPO> productByCodeCache = new HashMap<>(); final ConcurrentHashMap<String, ProductSpecPO> specByCodeCache = new ConcurrentHashMap<>();
final Map<String, ProductPO> productByNameCache = new HashMap<>(); final ConcurrentHashMap<String, ProductPO> productByCodeCache = new ConcurrentHashMap<>();
final Map<Long, ProductPO> productByIdCache = new HashMap<>(); final ConcurrentHashMap<String, ProductPO> productByNameCache = new ConcurrentHashMap<>();
final Map<String, Long> statusIdByNameCache = new HashMap<>(); final ConcurrentHashMap<Long, ProductPO> productByIdCache = new ConcurrentHashMap<>();
final Set<String> existingPlatformOrderNos = new HashSet<>(); final ConcurrentHashMap<String, Long> statusIdByNameCache = new ConcurrentHashMap<>();
final Map<String, Long> existingOrderIdByPlatformNo = new HashMap<>();
final Set<String> existingRelationKeys = new HashSet<>();
final List<PendingOrderInsert> pendingOrders = new ArrayList<>();
final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = new HashMap<>();
final List<ShopProductRelationPO> pendingRelations = new ArrayList<>();
final Set<String> pendingRelationKeys = new HashSet<>();
final Set<String> pendingPlatformOrderNos = new HashSet<>();
public ImportRuntimeContext(Long companyId, Long shopId, Long createBy) { // 已存在于 DB 的数据:预加载时填充(只写一次),后续只读
final Set<String> existingPlatformOrderNos = ConcurrentHashMap.newKeySet();
final Map<String, Long> existingOrderIdByPlatformNo = new ConcurrentHashMap<>();
final Set<String> existingRelationKeys = ConcurrentHashMap.newKeySet();
// pendingOrders:由 workers 并发添加(CopyOnWriteArrayList 读多写少场景高效)
final CopyOnWriteArrayList<PendingOrderInsert> pendingOrders = new CopyOnWriteArrayList<>();
// pendingOrderByPlatformNo:workers 并发 put,flush 时读取并清空
final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = Collections.synchronizedMap(new HashMap<>());
// pendingPlatformOrderNos:workers 并发 add,flush 时读取并清空
final Set<String> pendingPlatformOrderNos = Collections.synchronizedSet(new HashSet<>());
// pendingRelations:workers 并发添加,flush 时整体替换
final CopyOnWriteArrayList<ShopProductRelationPO> pendingRelations = new CopyOnWriteArrayList<>();
final Set<String> pendingRelationKeys = Collections.synchronizedSet(new HashSet<>());
public ImportRuntimeContext(Long companyId, Long shopId, Long createBy, Long taskId) {
this.companyId = companyId; this.companyId = companyId;
this.shopId = shopId; this.shopId = shopId;
this.createBy = createBy; this.createBy = createBy;
this.taskId = taskId;
} }
public Long getCompanyId() { return companyId; } public Long getCompanyId() { return companyId; }
public Long getShopId() { return shopId; } public Long getShopId() { return shopId; }
public Long getCreateBy() { return createBy; } public Long getCreateBy() { return createBy; }
public Long getTaskId() { return taskId; }
public DateTimeFormatPattern getDetectedDatePattern() { return detectedDatePattern; } public DateTimeFormatPattern getDetectedDatePattern() { return detectedDatePattern; }
public void setDetectedDatePattern(DateTimeFormatPattern detectedDatePattern) { this.detectedDatePattern = detectedDatePattern; } public void setDetectedDatePattern(DateTimeFormatPattern detectedDatePattern) { this.detectedDatePattern = detectedDatePattern; }
public Map<String, ProductSpecPO> getSpecByCodeCache() { return specByCodeCache; } public Map<String, ProductSpecPO> getSpecByCodeCache() { return specByCodeCache; }
@@ -167,7 +167,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
} }
Charset charset = detectFileEncoding(fileInputStream); Charset charset = detectFileEncoding(fileInputStream);
ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy()); ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy(), task.getId());
java.util.function.BiConsumer<Integer, Integer> progressCallback = (total, done) -> { java.util.function.BiConsumer<Integer, Integer> progressCallback = (total, done) -> {
updateTaskStatus(task.getId(), "processing", null, total, done, 0); updateTaskStatus(task.getId(), "processing", null, total, done, 0);
@@ -26,19 +26,28 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.*; import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
/** /**
* 订单导入核心处理器 * 订单导入核心处理器(并行版本)
* <p> * <p>
* 职责:CSV 解析 → 商品/规格解析 → 订单构建 → 批量插入 * 架构:生产者-消费者模型
* 不涉及:任务状态管理、文件获取、SSE 通知(由调用方负责) * - 主线程(生产者):读 CSV,解析行(CSV 字段 → CreateOrderDTO),放入队列
* - N 个 Worker 线程(消费者):从队列取 PendingRow,执行商品/规格解析,构建 OrderPO
* - 主线程:定时/定量 flush
*/ */
public class OrderImportProcessor { public class OrderImportProcessor {
private static final int ORDER_BATCH_SIZE = 1000; private static final int ORDER_BATCH_SIZE = 1000;
private static final int RELATION_BATCH_SIZE = 500; private static final int RELATION_BATCH_SIZE = 500;
private static final int IN_QUERY_BATCH_SIZE = 1000; private static final int IN_QUERY_BATCH_SIZE = 1000;
private static final int PARALLELISM = 4; // Worker 线程数
private static final int WORKER_TERMINATE_TIMEOUT_SEC = 60; // awaitTermination 超时
private final ProductSpecImportHelper specHelper; private final ProductSpecImportHelper specHelper;
private final OrderMapper orderMapper; private final OrderMapper orderMapper;
@@ -55,6 +64,89 @@ public class OrderImportProcessor {
this.sqlSessionFactory = sqlSessionFactory; this.sqlSessionFactory = sqlSessionFactory;
} }
// ==================== 生产者-消费者数据结构 ====================
/**
* 队列元素:原始 CSV 行数据(由主线程解析出,传递给 workers)
*/
public static class PendingRow {
public final int rowNumber;
public final CSVRecord record;
public final CreateOrderDTO dto; // 主线程已解析好的 DTO
public final Map<String, ImportRuntimeContext.MappingField> fieldMapping;
public final Map<String, Long> statusMapping;
public final Long shopId;
public final Long companyId;
public final Long createBy;
/** 无参构造器,用于毒丸(poison pill)信号 */
public PendingRow() {
this.rowNumber = -1;
this.record = null;
this.dto = null;
this.fieldMapping = null;
this.statusMapping = null;
this.shopId = null;
this.companyId = null;
this.createBy = null;
}
public PendingRow(int rowNumber, CSVRecord record, CreateOrderDTO dto,
Map<String, ImportRuntimeContext.MappingField> fieldMapping,
Map<String, Long> statusMapping,
Long shopId, Long companyId, Long createBy) {
this.rowNumber = rowNumber;
this.record = record;
this.dto = dto;
this.fieldMapping = fieldMapping;
this.statusMapping = statusMapping;
this.shopId = shopId;
this.companyId = companyId;
this.createBy = createBy;
}
}
/**
* Worker → 主线程的结果包装器
*/
public static class OrderParseResult {
public final int rowNumber;
public final CreateOrderDTO dto;
public final OrderPO order;
public final String platformOrderNo;
public final StringBuilder updateMsg;
public final boolean isUpdate;
public final Exception parseException;
private OrderParseResult(int rowNumber, CreateOrderDTO dto, OrderPO order,
String platformOrderNo, StringBuilder updateMsg,
boolean isUpdate, Exception parseException) {
this.rowNumber = rowNumber;
this.dto = dto;
this.order = order;
this.platformOrderNo = platformOrderNo;
this.updateMsg = updateMsg;
this.isUpdate = isUpdate;
this.parseException = parseException;
}
public static OrderParseResult success(int rowNumber, CreateOrderDTO dto, OrderPO order,
String platformOrderNo, boolean isUpdate) {
return new OrderParseResult(rowNumber, dto, order, platformOrderNo, null, isUpdate, null);
}
public static OrderParseResult error(int rowNumber, Exception e) {
return new OrderParseResult(rowNumber, null, null, null, null, false, e);
}
public static OrderParseResult error(int rowNumber, String platformOrderNo,
StringBuilder updateMsg, boolean isUpdate) {
return new OrderParseResult(rowNumber, null, null, platformOrderNo, updateMsg, isUpdate, null);
}
}
// ==================== 入口方法 ====================
/** /**
* 处理订单导入(入口方法,由 ImportTaskProcessorServiceImpl.processOrderImport 调用) * 处理订单导入(入口方法,由 ImportTaskProcessorServiceImpl.processOrderImport 调用)
*/ */
@@ -78,13 +170,13 @@ public class OrderImportProcessor {
.setTrim(true) .setTrim(true)
.build())) { .build())) {
// 收集预加载数据 // 收集预加载数据(主线程,单例执行)
ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code"); ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code");
ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code"); ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code");
ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name"); ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name");
ImportRuntimeContext.MappingField orderStatusField = fieldMapping.get("status"); ImportRuntimeContext.MappingField orderStatusField = fieldMapping.get("status");
ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no");
ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_date"); ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_time");
Set<String> specCodes = new HashSet<>(); Set<String> specCodes = new HashSet<>();
Set<String> productCodes = new HashSet<>(); Set<String> productCodes = new HashSet<>();
@@ -109,7 +201,7 @@ public class OrderImportProcessor {
} }
result.totalCount = records.size(); result.totalCount = records.size();
// 预加载 // 预加载(主线程)
specHelper.preloadProductSpecs(context, specCodes); specHelper.preloadProductSpecs(context, specCodes);
specHelper.preloadProductsByCode(context, productCodes); specHelper.preloadProductsByCode(context, productCodes);
specHelper.preloadProductsByName(context, productNames); specHelper.preloadProductsByName(context, productNames);
@@ -117,49 +209,49 @@ public class OrderImportProcessor {
specHelper.preloadStatuses(context, statusNames, statusMapping); specHelper.preloadStatuses(context, statusNames, statusMapping);
specHelper.preloadShopProductRelations(context, shopProductRelationMapper); specHelper.preloadShopProductRelations(context, shopProductRelationMapper);
// ========== 并行处理 ==========
// 无界队列:主线程 offer 永不阻塞,workers poll 获取行数据
LinkedBlockingQueue<PendingRow> workQueue = new LinkedBlockingQueue<>();
List<OrderParseResult> results = Collections.synchronizedList(new ArrayList<>());
ExecutorService workerPool = Executors.newFixedThreadPool(PARALLELISM);
// 启动 worker 线程
for (int i = 0; i < PARALLELISM; i++) {
workerPool.submit(() -> processWorkerLoop(workQueue, results, context));
}
StringBuilder errorMessages = new StringBuilder(); StringBuilder errorMessages = new StringBuilder();
// 主线程:生产 CSV 行数据
for (int i = 0; i < records.size(); i++) { for (int i = 0; i < records.size(); i++) {
CSVRecord record = records.get(i); CSVRecord record = records.get(i);
int rowNumber = i + 2; int rowNumber = i + 2;
try { try {
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, // 在主线程完成 CSV 解析(DTO 字段填充)
CreateOrderDTO dto = parseOrderFromCSV(record, fieldMapping, statusMapping,
task.getShopId(), context.getCompanyId(), context.getCreateBy(), context); task.getShopId(), context.getCompanyId(), context.getCreateBy(), context);
queueShopProductRelation(orderDTO, context); PendingRow row = new PendingRow(rowNumber, record, dto, fieldMapping, statusMapping,
OrderPO orderPO = buildOrderPO(orderDTO, context.getCompanyId(), task.getShopId(), context.getCompanyId(), context.getCreateBy());
context.getCreateBy(), task.getId(), context); workQueue.offer(row);
StringBuilder updateMsg = new StringBuilder(); // 关系入队(主线程直接处理,轻量)
if (orderDTO.getExistingOrderId() != null) { queueShopProductRelation(dto, context);
updateMsg.append(String.format("平台订单号 %s 已更新", orderDTO.getPlatformOrderNo()));
}
boolean isDuplicate = validatePlatformOrderNo(
orderDTO.getPlatformOrderNo(), context, orderPO,
rowNumber, orderPO.getId(), updateMsg);
if (!isDuplicate) {
ImportRuntimeContext.PendingOrderInsert pending =
new ImportRuntimeContext.PendingOrderInsert(
rowNumber, orderDTO.getPlatformOrderNo(), orderPO,
orderPO.getId(), updateMsg);
context.pendingOrders.add(pending);
if (orderDTO.getPlatformOrderNo() != null
&& !orderDTO.getPlatformOrderNo().trim().isEmpty()) {
context.pendingOrderByPlatformNo.put(
orderDTO.getPlatformOrderNo().trim(), pending);
}
}
// 关系批量 flush
if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) { if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) {
flushPendingRelations(context); flushPendingRelations(context);
} }
// 定期 flush 订单(主线程执行,避免多线程竞争 flush 锁)
if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) { if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) {
int[] r = flushPendingOrders(context, errorMessages); // 等待 workers 清空当前 pendingOrders
result.successCount += r[0]; waitForBatchFlush(context);
result.failCount += r[1]; int[] r = doFlushPendingOrders(context, errorMessages);
// successCount/failCount 已由主循环的 i+1-fail 覆盖,不累加
// 只累加 insert/update 计数
result.insertCount += r[0]; result.insertCount += r[0];
result.updateCount += r[2]; result.updateCount += r[2];
} }
@@ -178,14 +270,34 @@ public class OrderImportProcessor {
} }
} }
// 主线程生产完毕,向队列发送毒丸,通知 workers 停止
for (int i = 0; i < PARALLELISM; i++) {
workQueue.offer(new PendingRow()); // 空行,worker 收到后退出
}
// 等待所有 worker 退出(优雅关闭 + 有序退出)
workerPool.shutdown();
try {
if (!workerPool.awaitTermination(WORKER_TERMINATE_TIMEOUT_SEC, TimeUnit.SECONDS)) {
// 超时强制中断(兜底)
workerPool.shutdownNow();
}
} catch (InterruptedException e) {
workerPool.shutdownNow();
Thread.currentThread().interrupt();
}
// 合并 worker 结果到 pendingOrders(持有锁)
drainResultsToPendingOrders(results, context);
// 最终 flush // 最终 flush
int[] r = flushPendingOrders(context, errorMessages); int[] r = doFlushPendingOrders(context, errorMessages);
result.successCount += r[0];
result.failCount += r[1];
result.insertCount += r[0]; result.insertCount += r[0];
result.updateCount += r[2]; result.updateCount += r[2];
flushPendingRelations(context); flushPendingRelations(context);
// successCount/failCount 由主循环的 i+1-fail 统一计算,不从 flush 累加
result.successCount = records.size() - result.failCount;
result.errorMessages = errorMessages; result.errorMessages = errorMessages;
} catch (Exception e) { } catch (Exception e) {
@@ -195,9 +307,345 @@ public class OrderImportProcessor {
return result; return result;
} }
// ==================== CSV 解析 ==================== // ==================== Worker 线程循环 ====================
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, /**
* Worker 线程主循环:从队列取 PendingRow,执行商品/规格解析,构建 OrderPO,写入 results
*/
private void processWorkerLoop(LinkedBlockingQueue<PendingRow> workQueue,
List<OrderParseResult> results,
ImportRuntimeContext context) {
while (!Thread.currentThread().isInterrupted()) {
PendingRow row;
try {
row = workQueue.poll(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
if (row == null) continue;
// 毒丸:主线程发送的空行,表示结束
if (row.rowNumber < 0) {
break;
}
try {
// 执行商品/规格解析(Worker 线程)
CreateOrderDTO dto = resolveProductAndSpec(row, context);
// 构建 OrderPO
OrderPO orderPO = buildOrderPO(dto, context.getCompanyId(),
context.getCreateBy(), context.getTaskId(), context);
// 检查是否为更新
String platformOrderNo = dto.getPlatformOrderNo();
boolean isUpdate = false;
if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) {
String normalized = platformOrderNo.trim();
synchronized (context.pendingPlatformOrderNos) {
if (context.pendingPlatformOrderNos.contains(normalized)) {
isUpdate = true;
}
}
}
results.add(OrderParseResult.success(row.rowNumber, dto, orderPO,
platformOrderNo, isUpdate));
} catch (Exception e) {
results.add(OrderParseResult.error(row.rowNumber, e));
}
}
}
// ==================== 商品/规格解析(Worker 线程执行) ====================
/**
* 根据 PendingRow 中的 DTO,执行商品/规格查找/创建
* 此方法运行在 Worker 线程中,只做商品规格逻辑,不做 CSV 解析
*/
private CreateOrderDTO resolveProductAndSpec(PendingRow row, ImportRuntimeContext context) {
CreateOrderDTO dto = row.dto;
Long companyId = row.companyId;
String specCode = dto.getPlatformOrderNo() != null ? null : null; // DTO中无specCode,需从record重新获取
// 重新从 CSVRecord 获取 specCode(Worker 不能直接访问 CSVRecordParser)
// 方案:从 DTO 中取,或者在 parseOrderFromCSV 时预存
// 由于 parseOrderFromCSV 已填充了 productId/specId,此处只处理找不到的情况
if (dto.getProductSpecId() == null) {
// 重新获取关键字段
String specCodeRaw = getValue(row.record, row.fieldMapping.get("spec_code"));
String productCode = getValue(row.record, row.fieldMapping.get("product_code"));
String linkProductName = getValue(row.record, row.fieldMapping.get("link_product_name"));
String linkSpecName = getValue(row.record, row.fieldMapping.get("link_spec_name"));
if (specCodeRaw != null) specCodeRaw = specCodeRaw.trim();
if (productCode != null) productCode = productCode.trim().isEmpty() ? null : productCode.trim();
if (linkProductName != null) {
linkProductName = linkProductName.trim();
if (linkProductName.isEmpty()) linkProductName = null;
}
if (linkSpecName != null) {
linkSpecName = linkSpecName.trim();
if (linkSpecName.isEmpty()) linkSpecName = null;
}
if (specCodeRaw == null && productCode == null && linkProductName == null) {
throw new BusinessException("商品信息为空");
}
ProductSpecPO productSpec = null;
boolean isNewSpecCreated = false;
if (specCodeRaw != null && !specCodeRaw.isEmpty()) {
productSpec = specHelper.findProductSpecBySpecCode(specCodeRaw, companyId, context);
}
if (productSpec == null) {
top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product = null;
if (productCode != null) {
product = specHelper.findProductByProductCode(productCode, companyId, context);
}
if (product == null && linkProductName != null) {
product = specHelper.findProductByName(linkProductName, companyId, context);
}
if (product != null) {
String finalSpecName = (linkSpecName != null) ? linkSpecName : "未知规格";
productSpec = specHelper.createSpecForProduct(
companyId, product.getId(), finalSpecName,
specCodeRaw != null ? specCodeRaw : null,
row.createBy, context);
isNewSpecCreated = true;
} else {
String finalProductName = (linkProductName != null) ? linkProductName : "未知商品";
String finalSpecName = (linkSpecName != null) ? linkSpecName : "未知规格";
productSpec = specHelper.createProductAndSpecIfNotExists(
companyId, finalProductName, productCode,
finalSpecName, specCodeRaw,
row.createBy, context);
isNewSpecCreated = true;
}
}
if (productSpec == null) {
throw new BusinessException("无法创建商品规格");
}
dto.setProductId(productSpec.getProductId());
dto.setProductSpecId(productSpec.getId());
dto.setConfirm(isNewSpecCreated ? 0 : 1);
// linkProductName / linkSpecName fallback
if (dto.getLinkProductName() == null || dto.getLinkProductName().isEmpty()) {
top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product =
specHelper.getProductById(productSpec.getProductId(), context);
dto.setLinkProductName(product != null ? product.getName() : "未知商品");
}
if (dto.getLinkSpecName() == null || dto.getLinkSpecName().isEmpty()) {
dto.setLinkSpecName(productSpec.getName());
}
// 成本快照
dto.setProductCost(productSpec.getProductCost() != null ? productSpec.getProductCost() : BigDecimal.ZERO);
dto.setShippingCost(productSpec.getShippingCost() != null ? productSpec.getShippingCost() : BigDecimal.ZERO);
dto.setOtherCost(productSpec.getOtherCost() != null ? productSpec.getOtherCost() : BigDecimal.ZERO);
}
return dto;
}
// ==================== 批量 flush ====================
/**
* 将 worker 的结果合并到 context.pendingOrders(主线程调用,持有锁)
*/
private void drainResultsToPendingOrders(List<OrderParseResult> results,
ImportRuntimeContext context) {
synchronized (context.pendingOrders) {
for (OrderParseResult r : results) {
if (r.parseException != null) {
// 错误结果在主线程 parse 时已处理
continue;
}
StringBuilder updateMsg = new StringBuilder();
boolean isUpdate = r.isUpdate;
if (isUpdate) {
updateMsg.append(String.format("平台订单号 %s 已更新", r.platformOrderNo));
}
ImportRuntimeContext.PendingOrderInsert pending =
new ImportRuntimeContext.PendingOrderInsert(
r.rowNumber, r.platformOrderNo, r.order,
r.order.getId(), updateMsg);
context.pendingOrders.add(pending);
if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) {
synchronized (context.pendingOrderByPlatformNo) {
context.pendingOrderByPlatformNo.put(r.platformOrderNo.trim(), pending);
}
synchronized (context.pendingPlatformOrderNos) {
context.pendingPlatformOrderNos.add(r.platformOrderNo.trim());
}
}
}
results.clear();
}
}
/**
* 等待 workers 把当前 pendingOrders 消费完(flushed)
* 通过轮询 pendingOrders size 为 0 实现,最多等待 30 秒
*/
private void waitForBatchFlush(ImportRuntimeContext context) {
long deadline = System.currentTimeMillis() + 30_000;
while (context.pendingOrders.size() > 0 && System.currentTimeMillis() < deadline) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
private int[] doFlushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) {
synchronized (context.pendingOrders) {
if (context.pendingOrders.isEmpty()) {
return new int[] {0, 0, 0, 0};
}
return flushPendingOrdersInternal(context, errorMessages);
}
}
private int[] flushPendingOrdersInternal(ImportRuntimeContext context, StringBuilder errorMessages) {
int insertSuccess = 0, insertFail = 0, updateSuccess = 0, updateFail = 0;
List<ImportRuntimeContext.PendingOrderInsert> batch =
new ArrayList<>(context.pendingOrders);
List<ImportRuntimeContext.PendingOrderInsert> inserts = new ArrayList<>();
List<ImportRuntimeContext.PendingOrderInsert> updates = new ArrayList<>();
for (ImportRuntimeContext.PendingOrderInsert p : batch) {
(p.existingOrderId != null ? updates : inserts).add(p);
}
if (!inserts.isEmpty()) {
int[] r = doBatchInsert(inserts, context, errorMessages);
insertSuccess += r[0];
insertFail += r[1];
}
for (ImportRuntimeContext.PendingOrderInsert p : updates) {
try {
orderMapper.updateById(p.order);
updateSuccess++;
if (p.updateMessages != null && p.updateMessages.length() > 0) {
errorMessages.append(String.format("[更新] 第%d行:%s",
p.rowNumber, p.updateMessages.toString()))
.append(System.lineSeparator());
}
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception e) {
updateFail++;
errorMessages.append(String.format("[失败] 第%d行:更新失败 %s",
p.rowNumber, e.getMessage()))
.append(System.lineSeparator());
}
}
context.pendingOrders.clear();
synchronized (context.pendingOrderByPlatformNo) {
context.pendingOrderByPlatformNo.clear();
}
synchronized (context.pendingPlatformOrderNos) {
context.pendingPlatformOrderNos.clear();
}
return new int[] {insertSuccess, insertFail, updateSuccess, updateFail};
}
private int[] doBatchInsert(List<ImportRuntimeContext.PendingOrderInsert> inserts,
ImportRuntimeContext context, StringBuilder errorMessages) {
int success = 0, fail = 0;
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
OrderMapper batchMapper = session.getMapper(OrderMapper.class);
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
batchMapper.insert(p.order);
}
session.flushStatements();
session.commit();
success += inserts.size();
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
}
} catch (Exception e) {
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
try {
orderMapper.insert(p.order);
success++;
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception singleEx) {
fail++;
if (p.platformOrderNo != null) {
context.pendingPlatformOrderNos.remove(p.platformOrderNo.trim());
}
errorMessages.append(String.format("第%d行:%s",
p.rowNumber, singleEx.getMessage()))
.append(System.lineSeparator());
}
}
}
return new int[] {success, fail};
}
private void flushPendingRelations(ImportRuntimeContext context) {
if (context.pendingRelations.isEmpty()) return;
synchronized (context.pendingRelations) {
if (context.pendingRelations.isEmpty()) return;
List<ShopProductRelationPO> batch = new ArrayList<>(context.pendingRelations);
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
ShopProductRelationMapper batchMapper = session.getMapper(ShopProductRelationMapper.class);
for (ShopProductRelationPO relation : batch) {
batchMapper.insert(relation);
}
session.flushStatements();
session.commit();
for (ShopProductRelationPO relation : batch) {
context.existingRelationKeys.add(
context.buildRelationKey(relation.getShopId(), relation.getProductId()));
}
} catch (Exception e) {
for (ShopProductRelationPO relation : batch) {
try {
shopProductRelationMapper.insert(relation);
context.existingRelationKeys.add(
context.buildRelationKey(relation.getShopId(), relation.getProductId()));
} catch (Exception ignored) {}
}
} finally {
context.pendingRelations.clear();
context.pendingRelationKeys.clear();
}
}
}
// ==================== CSV 解析(主线程执行) ====================
/**
* 解析 CSV 行,填充 CreateOrderDTO(主线程执行)
* 注意:商品/规格解析(resolveProductAndSpec)由 Worker 线程异步执行
*/
CreateOrderDTO parseOrderFromCSV(CSVRecord record,
Map<String, ImportRuntimeContext.MappingField> fieldMapping, Map<String, ImportRuntimeContext.MappingField> fieldMapping,
Map<String, Long> statusMapping, Map<String, Long> statusMapping,
Long shopId, Long companyId, Long createBy, Long shopId, Long companyId, Long createBy,
@@ -243,7 +691,7 @@ public class OrderImportProcessor {
ImportRuntimeContext.MappingField shippingCostField = fieldMapping.get("shipping_cost"); ImportRuntimeContext.MappingField shippingCostField = fieldMapping.get("shipping_cost");
ImportRuntimeContext.MappingField otherCostField = fieldMapping.get("other_cost"); ImportRuntimeContext.MappingField otherCostField = fieldMapping.get("other_cost");
ImportRuntimeContext.MappingField receivedAmountField = fieldMapping.get("received_amount"); ImportRuntimeContext.MappingField receivedAmountField = fieldMapping.get("received_amount");
ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_date"); ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_time");
String specCode = getValue(record, specCodeField); String specCode = getValue(record, specCodeField);
if (specCode == null || specCode.trim().isEmpty()) { if (specCode == null || specCode.trim().isEmpty()) {
@@ -309,73 +757,10 @@ public class OrderImportProcessor {
if (linkSpecName.isEmpty()) linkSpecName = null; if (linkSpecName.isEmpty()) linkSpecName = null;
} }
// 商品/规格解析
if (specCode == null && productCode == null && linkProductName == null) {
throw new BusinessException("商品信息为空(商品编码/规格编码/商品名称至少要填一个)");
}
ProductSpecPO productSpec = null;
boolean isNewSpecCreated = false;
if (specCode != null && !specCode.trim().isEmpty()) {
productSpec = specHelper.findProductSpecBySpecCode(specCode, companyId, context);
}
if (productSpec == null) {
top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product = null;
if (productCode != null && !productCode.isEmpty()) {
product = specHelper.findProductByProductCode(productCode, companyId, context);
}
if (product == null && linkProductName != null && !linkProductName.isEmpty()) {
product = specHelper.findProductByName(linkProductName, companyId, context);
}
if (product != null) {
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = specHelper.createSpecForProduct(companyId, product.getId(), finalSpecName,
specCode != null ? specCode.trim() : null, createBy, context);
isNewSpecCreated = true;
} else {
String finalProductName = (linkProductName != null && !linkProductName.isEmpty()) ? linkProductName : "未知商品";
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = specHelper.createProductAndSpecIfNotExists(
companyId, finalProductName, productCode, finalSpecName,
specCode != null ? specCode.trim() : null,
createBy, context);
isNewSpecCreated = true;
}
}
if (productSpec == null) {
throw new BusinessException("无法创建商品规格");
}
dto.setProductId(productSpec.getProductId());
dto.setProductSpecId(productSpec.getId());
// 设置单件成本(从商品规格中获取,作为下单时快照)
dto.setProductCost(productSpec.getProductCost() != null ? productSpec.getProductCost() : BigDecimal.ZERO);
dto.setShippingCost(productSpec.getShippingCost() != null ? productSpec.getShippingCost() : BigDecimal.ZERO);
dto.setOtherCost(productSpec.getOtherCost() != null ? productSpec.getOtherCost() : BigDecimal.ZERO);
// 链接商品名称:优先使用CSV中的值,否则 fallback 到商品名称
if (linkProductName != null && !linkProductName.isEmpty()) {
dto.setLinkProductName(linkProductName); dto.setLinkProductName(linkProductName);
} else {
top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product =
specHelper.getProductById(productSpec.getProductId(), context);
dto.setLinkProductName(product != null ? product.getName() : "未知商品");
}
// 链接规格名称:优先使用CSV中的值,否则 fallback 到规格名称
if (linkSpecName != null && !linkSpecName.isEmpty()) {
dto.setLinkSpecName(linkSpecName); dto.setLinkSpecName(linkSpecName);
} else {
dto.setLinkSpecName(productSpec.getName());
}
// 如果创建了新规格,订单的确认状态设为0;否则设为1 // 数量(可能已在上面解析过,但这里也会重复解析,取后者)
dto.setConfirm(isNewSpecCreated ? 0 : 1);
// 数量
if (quantityField != null) { if (quantityField != null) {
String qtyStr = getValue(record, quantityField); String qtyStr = getValue(record, quantityField);
if (qtyStr != null && !qtyStr.trim().isEmpty()) { if (qtyStr != null && !qtyStr.trim().isEmpty()) {
@@ -395,7 +780,7 @@ public class OrderImportProcessor {
} }
} }
// 商品成本:优先使用 CSV 字段值,否则用规格中的快照值 // 商品成本
if (productCostField != null) { if (productCostField != null) {
String costStr = getValue(record, productCostField); String costStr = getValue(record, productCostField);
if (costStr != null && !costStr.trim().isEmpty()) { if (costStr != null && !costStr.trim().isEmpty()) {
@@ -447,6 +832,95 @@ public class OrderImportProcessor {
return dto; return dto;
} }
// ==================== 订单构建 ====================
/**
* 构建 OrderPO(Worker 线程调用)
*/
private OrderPO buildOrderPO(CreateOrderDTO dto, Long companyId, Long createBy,
Long importTaskId, ImportRuntimeContext context) {
OrderPO order = new OrderPO();
order.setCompanyId(companyId);
order.setShopId(dto.getShopId());
order.setPlatformOrderNo(dto.getPlatformOrderNo());
order.setStatusId(dto.getStatusId());
order.setProductId(dto.getProductId());
order.setProductSpecId(dto.getProductSpecId());
order.setLinkProductName(dto.getLinkProductName());
order.setLinkSpecName(dto.getLinkSpecName());
order.setQuantity(dto.getQuantity());
order.setUnitPrice(dto.getUnitPrice());
order.setProductCost(dto.getProductCost());
order.setShippingCost(dto.getShippingCost());
order.setOtherCost(dto.getOtherCost());
order.setReceivedAmount(dto.getReceivedAmount());
order.setOrderTime(dto.getOrderTime());
order.setCreateBy(createBy);
order.setImportTaskId(importTaskId);
order.setConfirm(dto.getConfirm() != null ? dto.getConfirm() : 1);
if (context != null && dto.getPlatformOrderNo() != null) {
String normalized = dto.getPlatformOrderNo().trim();
if (context.existingOrderIdByPlatformNo.containsKey(normalized)) {
order.setId(context.existingOrderIdByPlatformNo.get(normalized));
}
}
return order;
}
// ==================== 平台订单号校验 ====================
/**
* 校验平台订单号是否重复(主线程 flush 时调用,每次处理批量结果)
*/
private boolean validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context,
OrderPO newOrderPO, int newRowNumber,
Long newExistingOrderId, StringBuilder newUpdateMsg) {
if (platformOrderNo == null || platformOrderNo.trim().isEmpty()) return false;
String normalized = platformOrderNo.trim();
Long existingId = newExistingOrderId;
if (existingId == null && context.existingOrderIdByPlatformNo.containsKey(normalized)) {
existingId = context.existingOrderIdByPlatformNo.get(normalized);
}
if (context.pendingPlatformOrderNos.contains(normalized)) {
synchronized (context.pendingOrderByPlatformNo) {
ImportRuntimeContext.PendingOrderInsert existing =
context.pendingOrderByPlatformNo.get(normalized);
if (existing != null) {
existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber);
}
}
return true;
}
context.pendingPlatformOrderNos.add(normalized);
return false;
}
// ==================== 关系队列 ====================
/**
* 入队店铺-商品关联(主线程调用)
*/
private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) {
String relationKey = context.buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId());
if (context.existingRelationKeys.contains(relationKey)
|| context.pendingRelationKeys.contains(relationKey)) {
return;
}
ShopProductRelationPO relation = new ShopProductRelationPO();
relation.setCompanyId(context.getCompanyId());
relation.setShopId(orderDTO.getShopId());
relation.setProductId(orderDTO.getProductId());
relation.setSortOrder(0);
relation.setCreateBy(context.getCreateBy());
context.pendingRelations.add(relation);
context.pendingRelationKeys.add(relationKey);
}
// ==================== 日期解析 ====================
private LocalDateTime parseDateTime(String dateTimeStr, ImportRuntimeContext context) { private LocalDateTime parseDateTime(String dateTimeStr, ImportRuntimeContext context) {
if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) return null; if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) return null;
String trimmed = dateTimeStr.trim(); String trimmed = dateTimeStr.trim();
@@ -532,204 +1006,4 @@ public class OrderImportProcessor {
return null; return null;
} }
} }
private String removeBOM(String s) {
if (s == null) return null;
if (s.startsWith("\uFEFF")) return s.substring(1);
return s;
}
// ==================== 订单构建 ====================
private OrderPO buildOrderPO(CreateOrderDTO dto, Long companyId, Long createBy,
Long importTaskId, ImportRuntimeContext context) {
OrderPO order = new OrderPO();
order.setCompanyId(companyId);
order.setShopId(dto.getShopId());
order.setPlatformOrderNo(dto.getPlatformOrderNo());
order.setStatusId(dto.getStatusId());
order.setProductId(dto.getProductId());
order.setProductSpecId(dto.getProductSpecId());
order.setLinkProductName(dto.getLinkProductName());
order.setLinkSpecName(dto.getLinkSpecName());
order.setQuantity(dto.getQuantity());
order.setUnitPrice(dto.getUnitPrice());
order.setProductCost(dto.getProductCost());
order.setShippingCost(dto.getShippingCost());
order.setOtherCost(dto.getOtherCost());
order.setReceivedAmount(dto.getReceivedAmount());
order.setOrderTime(dto.getOrderTime());
order.setCreateBy(createBy);
order.setImportTaskId(importTaskId);
order.setConfirm(dto.getConfirm() != null ? dto.getConfirm() : 1);
if (context != null && dto.getPlatformOrderNo() != null) {
String normalized = dto.getPlatformOrderNo().trim();
if (context.existingOrderIdByPlatformNo.containsKey(normalized)) {
order.setId(context.existingOrderIdByPlatformNo.get(normalized));
}
}
return order;
}
// ==================== 平台订单号校验 ====================
private boolean validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context,
OrderPO newOrderPO, int newRowNumber,
Long newExistingOrderId, StringBuilder newUpdateMsg) {
if (platformOrderNo == null || platformOrderNo.trim().isEmpty()) return false;
String normalized = platformOrderNo.trim();
Long existingId = newExistingOrderId;
if (existingId == null && context.existingOrderIdByPlatformNo.containsKey(normalized)) {
existingId = context.existingOrderIdByPlatformNo.get(normalized);
}
if (context.pendingPlatformOrderNos.contains(normalized)) {
ImportRuntimeContext.PendingOrderInsert existing =
context.pendingOrderByPlatformNo.get(normalized);
if (existing != null) {
existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber);
}
return true;
}
context.pendingPlatformOrderNos.add(normalized);
return false;
}
// ==================== 关系队列 ====================
private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) {
String relationKey = context.buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId());
if (context.existingRelationKeys.contains(relationKey)
|| context.pendingRelationKeys.contains(relationKey)) {
return;
}
ShopProductRelationPO relation = new ShopProductRelationPO();
relation.setCompanyId(context.getCompanyId());
relation.setShopId(orderDTO.getShopId());
relation.setProductId(orderDTO.getProductId());
relation.setSortOrder(0);
relation.setCreateBy(context.getCreateBy());
context.pendingRelations.add(relation);
context.pendingRelationKeys.add(relationKey);
}
// ==================== 批量 flush ====================
private int[] flushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) {
if (context.pendingOrders.isEmpty()) {
return new int[] {0, 0, 0, 0};
}
int insertSuccess = 0, insertFail = 0, updateSuccess = 0, updateFail = 0;
List<ImportRuntimeContext.PendingOrderInsert> batch =
new ArrayList<>(context.pendingOrders);
List<ImportRuntimeContext.PendingOrderInsert> inserts = new ArrayList<>();
List<ImportRuntimeContext.PendingOrderInsert> updates = new ArrayList<>();
for (ImportRuntimeContext.PendingOrderInsert p : batch) {
(p.existingOrderId != null ? updates : inserts).add(p);
}
if (!inserts.isEmpty()) {
int[] r = doBatchInsert(inserts, context, errorMessages);
insertSuccess += r[0];
insertFail += r[1];
}
for (ImportRuntimeContext.PendingOrderInsert p : updates) {
try {
orderMapper.updateById(p.order);
updateSuccess++;
if (p.updateMessages != null && p.updateMessages.length() > 0) {
errorMessages.append(String.format("[更新] 第%d行:%s",
p.rowNumber, p.updateMessages.toString()))
.append(System.lineSeparator());
}
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception e) {
updateFail++;
errorMessages.append(String.format("[失败] 第%d行:更新失败 %s",
p.rowNumber, e.getMessage()))
.append(System.lineSeparator());
}
}
context.pendingOrders.clear();
return new int[] {insertSuccess, insertFail, updateSuccess, updateFail};
}
private int[] doBatchInsert(List<ImportRuntimeContext.PendingOrderInsert> inserts,
ImportRuntimeContext context, StringBuilder errorMessages) {
int success = 0, fail = 0;
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
OrderMapper batchMapper = session.getMapper(OrderMapper.class);
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
batchMapper.insert(p.order);
}
session.flushStatements();
session.commit();
success += inserts.size();
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
}
} catch (Exception e) {
for (ImportRuntimeContext.PendingOrderInsert p : inserts) {
try {
orderMapper.insert(p.order);
success++;
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
String normalized = p.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception singleEx) {
fail++;
if (p.platformOrderNo != null) {
context.pendingPlatformOrderNos.remove(p.platformOrderNo.trim());
}
errorMessages.append(String.format("第%d行:%s",
p.rowNumber, singleEx.getMessage()))
.append(System.lineSeparator());
}
}
}
return new int[] {success, fail};
}
private void flushPendingRelations(ImportRuntimeContext context) {
if (context.pendingRelations.isEmpty()) return;
List<ShopProductRelationPO> batch = new ArrayList<>(context.pendingRelations);
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
ShopProductRelationMapper batchMapper = session.getMapper(ShopProductRelationMapper.class);
for (ShopProductRelationPO relation : batch) {
batchMapper.insert(relation);
}
session.flushStatements();
session.commit();
for (ShopProductRelationPO relation : batch) {
context.existingRelationKeys.add(
context.buildRelationKey(relation.getShopId(), relation.getProductId()));
}
} catch (Exception e) {
for (ShopProductRelationPO relation : batch) {
try {
shopProductRelationMapper.insert(relation);
context.existingRelationKeys.add(
context.buildRelationKey(relation.getShopId(), relation.getProductId()));
} catch (Exception ignored) {}
}
} finally {
context.pendingRelations.clear();
context.pendingRelationKeys.clear();
}
}
} }