package com.ruoyi.jarvis.task; import com.ruoyi.jarvis.domain.JDOrder; import com.ruoyi.jarvis.service.IJDOrderService; import com.ruoyi.jarvis.service.ILogisticsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; /** * 物流信息扫描定时任务 * 每1小时扫描一次分销标记为F或PDD的订单,获取物流信息并推送 */ @Component public class LogisticsScanTask { private static final Logger logger = LoggerFactory.getLogger(LogisticsScanTask.class); @Resource private IJDOrderService jdOrderService; @Resource private ILogisticsService logisticsService; /** * 定时任务:每1小时执行一次 * Cron表达式:0 0 * * * ? 表示每小时的第0分钟执行 */ @Scheduled(cron = "0 0 * * * ?") public void scanAndFetchLogistics() { logger.info("========== 开始执行物流信息扫描定时任务 =========="); try { // 查询分销标记为F或PDD且有物流链接的订单 List orders = jdOrderService.selectJDOrderListByDistributionMarkFOrPDD(); if (orders == null || orders.isEmpty()) { logger.info("未找到需要处理的订单"); return; } logger.info("找到 {} 个需要处理的订单", orders.size()); int processedCount = 0; int skippedCount = 0; int successCount = 0; int failedCount = 0; // 串行处理订单(避免并发调用接口) for (JDOrder order : orders) { try { // 检查Redis中是否已处理过(避免重复处理) if (logisticsService.isOrderProcessed(order.getId())) { logger.debug("订单已处理过,跳过 - 订单ID: {}", order.getId()); skippedCount++; continue; } logger.info("开始处理订单 - 订单ID: {}, 订单号: {}, 分销标识: {}", order.getId(), order.getOrderId(), order.getDistributionMark()); // 获取物流信息并推送(串行执行,不并发) boolean success = logisticsService.fetchLogisticsAndPush(order); if (success) { successCount++; logger.info("订单处理成功 - 订单ID: {}, 订单号: {}", order.getId(), order.getOrderId()); } else { failedCount++; logger.warn("订单处理失败 - 订单ID: {}, 订单号: {}", order.getId(), order.getOrderId()); } processedCount++; // 添加短暂延迟,避免请求过于频繁 Thread.sleep(500); // 每次请求间隔500毫秒 } catch (InterruptedException e) { logger.error("定时任务被中断", e); Thread.currentThread().interrupt(); break; } catch (Exception e) { failedCount++; logger.error("处理订单时发生异常 - 订单ID: {}, 错误: {}", order.getId(), e.getMessage(), e); // 继续处理下一个订单 } } logger.info("========== 物流信息扫描定时任务执行完成 =========="); logger.info("总订单数: {}, 已处理: {}, 跳过: {}, 成功: {}, 失败: {}", orders.size(), processedCount, skippedCount, successCount, failedCount); } catch (Exception e) { logger.error("执行物流信息扫描定时任务时发生异常", e); } } }