Commit 4cf275e9 by 叶立庆

Merge branch 'v5.8.8' into 'master'

上线合并

See merge request !59
2 parents ef493c16 1bd44df1
......@@ -99,5 +99,10 @@ public interface MerchantGoodsInfoMapper extends OreMapper<MerchantGoodsInfo> {
List<MerchantGoodsInfo> listByMerchantGoodsCodes(@Param("idList") List<Integer> idList);
List<MerchantGoodsInfo> querySourceGoodsInfo();
/**
* 查询指定时间之后有更新的上架商品 id
*/
List<Integer> listUpdatedGoodsIds(@Param("updatedDateStart") String updatedDateStart);
}
......@@ -25,4 +25,9 @@ public interface VdRuleMapper extends OreMapper<VdRule> {
@MapKey("merchantId")
Map<Integer, VdRule> findMerchant(@Param("businessType") Integer businessType);
/**
* 查询已存在于规则表中的商品 id
*/
List<Integer> listExistGoodsIds(@Param("goodsIds") List<Integer> goodsIds);
}
\ No newline at end of file
package cn.com.glsx.dj.smartcarlife.service;
import cn.com.glsx.dj.smartcarlife.constant.CommonConstants;
import cn.com.glsx.dj.smartcarlife.enums.TaskWaitEnum;
import cn.com.glsx.dj.smartcarlife.enums.TaskWaitEnum.TaskWaitStatusEnum;
import cn.com.glsx.dj.smartcarlife.mapper.TaskWaitRecordMapper;
......@@ -68,6 +69,32 @@ public class TaskWaitRecordService {
}
}
/**
* 新增一条待执行任务记录
*/
@Transactional(propagation=Propagation.REQUIRED)
public void insertWaitTask(Byte taskType, String data){
RpcAssert.assertNotNull(taskType, DefaultErrorEnum.DATA_NULL,"taskType not be null");
RpcAssert.assertNotNull(data, DefaultErrorEnum.DATA_NULL,"data not be null");
try{
Date now = new Date();
TaskWaitRecord record = TaskWaitRecord.builder()
.data(data)
.taskType(taskType)
.status(TaskWaitStatusEnum.WAITING.getValue())
.createdBy(CommonConstants.DEFAULT_UPDATE_BY)
.createdDate(now)
.updatedBy(CommonConstants.DEFAULT_UPDATE_BY)
.updatedDate(now)
.deletedFlag("N")
.build();
taskWaitRecordMapper.insertSelective(record);
}catch(Exception e){
log.error(e.getMessage(),e);
throw new RpcServiceException(DefaultErrorEnum.DATABASE_ERROR,e.getMessage());
}
}
public void batchExecuteTask(TaskWaitEnum.TaskWaitTypeEnum taskType, TaskWaitActuator actuator){
RpcAssert.assertNotNull(taskType, DefaultErrorEnum.DATA_NULL,"taskType not be null");
try{
......
......@@ -13,6 +13,7 @@ import cn.com.glsx.dj.smartcarlife.enums.createBusinessApprove.ProductTypeEnum;
import cn.com.glsx.dj.smartcarlife.enums.createBusinessApprove.SystemStatusEnum;
import cn.com.glsx.dj.smartcarlife.manager.PushGoodsManager;
import cn.com.glsx.dj.smartcarlife.mapper.*;
import cn.com.glsx.dj.smartcarlife.mapper.vd.VdRuleMapper;
import cn.com.glsx.dj.smartcarlife.model.*;
import cn.com.glsx.dj.smartcarlife.response.goods.PackageGoodsResponse;
import cn.com.glsx.dj.smartcarlife.service.*;
......@@ -57,6 +58,8 @@ import tk.mybatis.mapper.entity.Example;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
......@@ -132,6 +135,9 @@ public class MerchantGoodsInfoService {
@Autowired
private GoodsCategoryConfigurationMapper goodsCategoryConfigurationMapper;
@Autowired
private VdRuleMapper vdRuleMapper;
/**
* 根据服务项目ID查询并组装展示字符串,格式:项目名称/用例标准
*/
......@@ -2703,12 +2709,51 @@ public class MerchantGoodsInfoService {
}
public void sendGoods() {
log.info("开始同步上架商品到SCRM");
// 先将昨日有更新、且未配置到VD规则表的商品补入待推送队列
try{
String yesterdayStart = LocalDate.now().minusDays(1).atStartOfDay()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
List<Integer> goodsIds = merchantGoodsInfoMapper.listUpdatedGoodsIds(yesterdayStart);
if(CollectionUtils.isNotEmpty(goodsIds)){
Set<Integer> existGoodsIds = new HashSet<>();
int batchSize = 500;
for(int i = 0; i < goodsIds.size(); i += batchSize){
List<Integer> batch = goodsIds.subList(i, Math.min(i + batchSize, goodsIds.size()));
List<Integer> existGoodsIdList = vdRuleMapper.listExistGoodsIds(batch);
if(CollectionUtils.isNotEmpty(existGoodsIdList)){
existGoodsIds.addAll(existGoodsIdList);
}
}
int addedCount = 0;
for(Integer goodsId : goodsIds){
if(existGoodsIds.contains(goodsId)){
continue;
}
try{
taskWaitRecordService.insertWaitTask(
TaskWaitEnum.TaskWaitTypeEnum.PUSH_GOODS_TO_SCRM.getValue(), String.valueOf(goodsId));
addedCount++;
}catch(Exception e){
log.error("新增待推送商品任务失败, goodsId:{}, error:{}", goodsId, e.getMessage(), e);
}
}
log.info("昨日更新商品补入待推送队列完成, 查询数量:{}, 已配置VD规则数量:{}, 新增数量:{}",
goodsIds.size(), existGoodsIds.size(), addedCount);
}
}catch(Exception e){
log.error("昨日更新商品补入待推送队列异常", e);
}
// 原推送商品逻辑
try{
log.info("开始同步上架商品到SCRM");
taskWaitRecordService.batchExecuteTask(TaskWaitEnum.TaskWaitTypeEnum.PUSH_GOODS_TO_SCRM,value -> {
MerchantGoodsInfoDTO goodsInfo = this.getDetailById(Integer.parseInt(value));
pushGoodsManager.sendGoods(goodsInfo, CommonConstants.DEFAULT_UPDATE_BY,true);
return true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return true;
});
}catch(Exception e){
log.error(e.getMessage(),e);
......
......@@ -1425,4 +1425,13 @@
mgi.scene_type = 0 and mgi.base_scene_code is null
and mgi.deleted_flag = 'N' and cc.category_name IN ('整车延保', '安心包', '轮胎', '电池延保');
</select>
<select id="listUpdatedGoodsIds" resultType="java.lang.Integer">
select a.id
from dj_car_life_merchant_goods_info a
where a.deleted_flag = 'N'
and a.status in (0, 1)
and a.scene_type = 0
<![CDATA[and a.updated_date >= #{updatedDateStart}]]>
</select>
</mapper>
......@@ -139,4 +139,14 @@
</if>
group by merchant_id
</select>
<select id="listExistGoodsIds" resultType="java.lang.Integer">
select b.goods_id
from dj_car_life_vd_rule_goods b
where b.deleted_flag = 'N'
and b.goods_id in
<foreach collection="goodsIds" item="goodsId" open="(" separator="," close=")">
#{goodsId}
</foreach>
</select>
</mapper>
\ No newline at end of file
  • @wangxw1
    commented
    Master

    一、关键问题与优化建议,如果必要,给出代码示例(仅限 Top 3)

    问题 1:缺少任务幂等校验与并发防重机制,可能导致重复推送或任务堆积
    • 问题描述:在 MerchantGoodsInfoService.sendGoods() 中,直接查询 updated_date >= yesterdayStart 的商品并调用 taskWaitRecordService.insertWaitTask 插入待执行任务,未校验 task_wait_record 表中是否已存在相同 taskType 且状态为 WAITING(或已推送)的记录;同时,若定时任务触发时间窗口跨天、任务重跑,或分布式环境下多节点并发执行 sendGoods(),会导致同一 goodsId 被重复写入队列。
    • 影响分析:重复任务会导致向 SCRM 系统重复推送相同的商品数据,不仅浪费下游接口资源与本地线程休眠时间,还可能覆盖下游状态或触发下游限流/幂等异常。
    • 优化建议:
      1. 在写入 task_wait_record 前,查询 task_wait_record 中 task_type = PUSH_GOODS_TO_SCRM 且状态为待执行(或近期已生成)的 data 集合进行去重过滤,或利用数据库唯一索引保证幂等。
      2. 对 sendGoods() 定时任务增加分布式锁(如 Redis 锁),防止多实例并发执行。
    • 代码示例: ```java // 1. 过滤掉已在待推送队列中的 goodsId(假设 taskWaitRecordService 提供查询待执行 data 的方法) Set waitingGoodsIds = taskWaitRecordService.listWaitingDataByType( TaskWaitEnum.TaskWaitTypeEnum.PUSH_GOODS_TO_SCRM.getValue());

    for (Integer goodsId : goodsIds) { String goodsIdStr = String.valueOf(goodsId); if (existGoodsIds.contains(goodsId) || waitingGoodsIds.contains(goodsIdStr)) { continue; } taskWaitRecordService.insertWaitTask( TaskWaitEnum.TaskWaitTypeEnum.PUSH_GOODS_TO_SCRM.getValue(), goodsIdStr); addedCount++; }

    
    ##### 问题 2:捕获 `InterruptedException` 后未恢复线程中断状态,且硬编码 `Thread.sleep(1000)` 存在阻塞风险
    * **问题描述**:在 `MerchantGoodsInfoService.sendGoods()` 的消费逻辑中,捕获 `InterruptedException` 后做了空 catch 处理,直接吞掉了中断信号;同时,在同步执行循环中固定休眠 1 秒,当待推送商品数量较大(如上千条)时,任务总耗时将达到数十分钟,容易引发定时任务调度超时或线程池阻塞。
    * **影响分析**:吞掉 `InterruptedException` 会导致应用优雅停机(Graceful Shutdown)或任务取消时,工作线程无法及时感知中断信号而正常退出;同步长耗时休眠会占用任务调度线程,影响同调度器下其他定时任务的正常触发。
    * **优化建议**:捕获 `InterruptedException` 时必须调用 `Thread.currentThread().interrupt()` 恢复中断标志并跳出循环;若需对下游做限流,建议使用 Guava `RateLimiter` 或在分布式任务配置中控制单次处理批量大小(Limit)。
    * **代码示例**:
    ```java
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        log.warn("同步上架商品到SCRM任务被中断, goodsId:{}", value);
        return false;
    }
    
    问题 3:循环内逐条执行数据库 INSERT,存在性能瓶颈;且 SQL 状态过滤语义与注释不一致
    • 问题描述:
      1. 在 MerchantGoodsInfoService.sendGoods() 中,通过 for 循环逐条调用 taskWaitRecordService.insertWaitTask(),每次插入都会开启独立事务并执行一次网络 I/O;当更新商品较多时,数据库连接和事务开销显著增加。
      2. 方法注释及日志均为“查询/同步上架商品”,但 MerchantGoodsInfoMapper.xml 中的条件为 a.status in (0, 1),若 0 和 1 分别代表下架/上架,则会将非上架商品一并纳入;若均为上架态,建议在注释或常量中明确说明,避免后续维护误解。
    • 影响分析:逐条插入在数据量较大时容易拖慢数据库写入性能并增加事务日志压力;状态条件若与业务语义不符,可能导致下架商品被误推至 SCRM。
    • 优化建议:在 TaskWaitRecordService 中提供批量插入方法 batchInsertWaitTask,按批次(如每批 500 条)执行批量写入;同时核对 status in (0, 1) 的业务枚举定义,使用明确的常量或补充注释。

    二、评分明细

    1. 功能实现的正确性与健壮性(29 / 40分)
      • 理由:核查了 MyBatis SQL 未使用子查询,且未修改 Dubbo Remote 接口参数,符合核心规范;分批(500条/批)查询 VdRuleMapper.listExistGoodsIds 避免了 SQL IN 列表过长问题。但缺少任务写入的幂等去重校验,吞掉了 InterruptedException 中断信号,且 SQL 中 status in (0, 1) 与“上架商品”的业务描述存在歧义风险。
    2. 安全性与潜在风险(27 / 30分)
      • 理由:SQL 均采用 #{} 预编译参数绑定,无 SQL 注入风险;VdRuleMapper.xml 仅在判断 CollectionUtils.isNotEmpty(goodsIds) 后调用,但 XML 层面未加 <if test="goodsIds != null and goodsIds.size() > 0"> 防护,若后续其他地方直接调用传入空集合会导致 SQL 语法错误(goods_id in ())。
    3. 最佳实践与可维护性(14 / 20分)
      • 理由:日志埋点较为清晰,记录了查询数量、已配置数量与新增数量;但存在空 catch 块、硬编码魔法值(batchSize = 500、Thread.sleep(1000)、status in (0, 1)),且 sendGoods() 方法职责过重,建议将“补入待推送队列”拆分为独立私有方法。
    4. 性能与资源利用(3 / 5分)
      • 理由:查询侧做了分批处理,但写入侧在 for 循环中逐条调用带 @Transactional 的 insertWaitTask,未采用批量插入;同步休眠 1 秒在高数据量下会长时间占用执行线程。
    5. 提交信息质量(3 / 5分)
      • 理由:业务提交信息“定期推送昨日有更新的上架商品数据”基本说明了功能意图,但缺少规范前缀(如 feat:)及关联需求/任务单号,且混入了分支合并记录,可追溯性一般。

    总分:76分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!