Commit 1bd44df1 by 周立明

定期推送昨日有更新的上架商品数据

1 parent ef493c16
......@@ -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. 性能与健壮性:在批处理循环中使用 Thread.sleep 并吞没中断异常(最重要)

    • 问题描述:在 MerchantGoodsInfoService.sendGoods 方法的原推送逻辑中,在 batchExecuteTask 的 Lambda 表达式内加入了 Thread.sleep(1000),并且捕获了 InterruptedException 但未作任何处理(空 catch 块)。
    • 影响分析:
      • 线程池耗尽风险:如果待推送的商品数量较多(例如 1000 个),该执行线程将被强行阻塞 1000 秒(超 15 分钟)。如果该方法运行在 Dubbo 业务线程池或定时任务线程池中,极易导致线程池资源耗尽,阻塞其他正常业务。
      • 破坏中断机制:吞没 InterruptedException 是一种严重的反模式。当应用进行优雅停机或线程池尝试中断任务时,该线程将无法响应中断信号,导致应用无法正常关闭。
    • 优化建议:
      • 如果是为了应对下游 SCRM 接口的限流,不应使用线程休眠,而应引入真正的限流器(如 Guava RateLimiter),或者将任务发送至 MQ,利用 MQ 的延迟消费或速率控制来平滑请求。
      • 如果必须保留 sleep,至少需要恢复线程的中断状态。
    • 代码示例: ```java // 建议方案一:使用 Guava RateLimiter (推荐) // private static final RateLimiter rateLimiter = RateLimiter.create(1.0); // 每秒1个请求 // rateLimiter.acquire();

    // 建议方案二:修复异常吞没 try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // 恢复中断状态 log.error("推送任务被中断", e); return false; }

    
    **2. 性能与资源利用:在 `for` 循环中频繁调用带有 `@Transactional` 的单条插入方法**
    - **问题描述**:在 `sendGoods` 方法中,遍历 `goodsIds` 并在循环体内部调用了 `taskWaitRecordService.insertWaitTask(...)`。而 `insertWaitTask` 方法标注了 `@Transactional(propagation=Propagation.REQUIRED)`。
    - **影响分析**:如果昨日更新的商品数量级较大,循环调用会导致数据库连接被频繁获取和释放,并开启/提交大量的独立事务。这不仅产生巨大的网络 I/O 和数据库性能开销,还极易引发数据库连接池被打满(Connection Pool Exhaustion)。
    - **优化建议**:在 `TaskWaitRecordService` 中新增一个批量插入的方法(如 `batchInsertWaitTasks`),在 MyBatis XML 中使用 `<foreach>` 标签实现单次批量 `INSERT`,并在 Service 层一次性组装好 List 后整体保存。
    - **代码示例**:
      ```java
      // 在 TaskWaitRecordService 中新增批量插入
      @Transactional(propagation = Propagation.REQUIRED)
      public void batchInsertWaitTasks(List<TaskWaitRecord> records) {
          if (CollectionUtils.isNotEmpty(records)) {
              taskWaitRecordMapper.insertList(records); // 需 Mapper 支持批量插入
          }
      }
    

    3. 最佳实践:MyBatis 中使用 String 类型进行日期比较存在隐患

    • 问题描述:listUpdatedGoodsIds 接口中入参 updatedDateStart 为 String 类型,在 XML 中直接与 updated_date(通常为 DATETIME 或 TIMESTAMP 类型)进行 >= 比较。
    • 影响分析:虽然 MySQL 具有隐式类型转换的能力,能够解析标准格式的日期字符串,但这会导致数据库无法完全利用日期类型的索引(视具体 MySQL 版本和配置而定),且在跨时区或数据库迁移时容易引发格式不匹配的运行时异常。
    • 优化建议:建议将 Mapper 接口和 XML 中的参数类型改为 java.util.Date 或 java.time.LocalDateTime。
    • 代码示例: ```java // Mapper 接口 List listUpdatedGoodsIds(@Param("updatedDateStart") LocalDateTime updatedDateStart);

    // Service 调用处 LocalDateTime yesterdayStart = LocalDate.now().minusDays(1).atStartOfDay(); List goodsIds = merchantGoodsInfoMapper.listUpdatedGoodsIds(yesterdayStart);

    
    ---
    
    #### 二、评分明细
    
    - **功能实现的正确性与健壮性(32 / 40分)**
      - **理由**:业务逻辑基本实现,集合分批查询(`subList`)处理得当,避免了 `IN` 语句超长。未违反 MyBatis 子查询禁用规则,未变更 Dubbo 接口参数。扣分点在于 `Thread.sleep` 的加入破坏了程序的健壮性,且吞没了中断异常。
    
    - **安全性与潜在风险(30 / 30分)**
      - **理由**:SQL 语句均使用了 `#{}` 参数化查询,无 SQL 注入风险;未发现越权或敏感信息泄露等安全漏洞。
    
    - **最佳实践与可维护性(12 / 20分)**
      - **理由**:代码结构尚可,但存在一些坏味道。例如:异常捕获后出现空代码块;在业务代码中硬编码了魔法值(如 `batchSize = 500`);在循环中调用事务方法违反了事务管理最佳实践。
    
    - **性能与资源利用(1 / 5分)**
      - **理由**:存在两个严重的性能瓶颈。第一,循环内开启数据库事务进行单条插入(N+1 问题);第二,在批处理工作线程中强制 `Thread.sleep(1000)`,极大地浪费了线程资源并拉长了执行时间。
    
    - **提交信息质量(4 / 5分)**
      - **理由**:“定期推送昨日有更新的上架商品数据”描述了核心业务变更,能够追溯代码意图,但未能说明修改原推送逻辑(加入休眠)的背景原因。
    
    总分:79分
    
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!