Commit fd92b92d by 林永健

feat(merchant-bi): 优化每日BI动态汇总推送逻辑

- 改为先查询昨日所有有新增策略/留言的门店列表,避免分页查询所有关注数据
- 合并内存计算,按门店ID和业务类型分组处理,提升数据处理效率
- 新增无关注人时仍推送给区域运营和线上运营的逻辑,保障关键人员接收动态
- 移除旧的分页查询及相关依赖,简化代码结构
- 新增接口查询指定时间段内有新增策略/留言的门店ID,支持昨日动态门店筛选
- 增加异常捕获和详细日志,提升任务执行稳定性和可追踪性
- 调整推送服务调用,分别处理运营人员和关注人推送场景
1 parent dc84266d
...@@ -10,10 +10,9 @@ import cn.com.glsx.dj.peanalysis.service.MerchantBasicInfoService; ...@@ -10,10 +10,9 @@ import cn.com.glsx.dj.peanalysis.service.MerchantBasicInfoService;
import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService; import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService;
import cn.com.glsx.dj.peanalysis.service.WechatPushService; import cn.com.glsx.dj.peanalysis.service.WechatPushService;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils; import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import cn.com.glsx.dj.strategy.model.StrategyInfo;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -57,27 +56,42 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -57,27 +56,42 @@ public class MerchantBiDailyPushJob implements SimpleJob {
public void execute(ShardingContext shardingContext) { public void execute(ShardingContext shardingContext) {
log.info("开始执行每日 BI 动态汇总推送任务"); log.info("开始执行每日 BI 动态汇总推送任务");
// 1. 分页获取所有存在关注的门店 + 业务组合 // 1. 查询昨日有新增策略/留言的门店 ID 列表
int pageNum = 1; List<StrategyInfo> yesterdayStrategy = commentService.findMerchantIdsWithYesterdayComments();
int pageSize = 500; // 每页处理 500 条记录 if (CollectionUtils.isEmpty(yesterdayStrategy)) {
Map<String, StoreSettingDTO> settingMap = new HashMap<>(); log.info("昨日无新增策略/留言,无需推送");
return;
while (true) { }
// 使用 PageHelper 进行分页查询 Map<Integer, Map<Integer, List<StrategyInfo>>> yesterdayDataMap = yesterdayStrategy.stream()
PageHelper.startPage(pageNum, pageSize); .collect(Collectors.groupingBy(StrategyInfo::getMerchantId, Collectors.groupingBy(StrategyInfo::getBiz, Collectors.toList())));
List<MerchantBiFollow> follows = followMapper.findAllActiveFollows(); List<Integer> activeMerchantIds = new ArrayList<>(yesterdayDataMap.keySet());
log.info("昨日有动态的门店数:{}", activeMerchantIds.size());
// 转换为 PageInfo 以获取分页信息 // 2. 获取这些门店的所有业务类型(1-延保,2-轻改,3-权益)
PageInfo<MerchantBiFollow> pageInfo = new PageInfo<>(follows); // List<Byte> businessTypes = Arrays.asList((byte)1, (byte)2, (byte)3);
// 3. 批量查询这些门店 + 业务的关注记录(只查询存在关注的组合)
List<MerchantBiFollow> follows = followMapper.findByMerchantIdsAndBiz(activeMerchantIds, null);
if (CollectionUtils.isEmpty(follows)) { if (CollectionUtils.isEmpty(follows)) {
log.info("分页查询完成,共处理{}页", pageNum - 1); log.info("这些门店均无关注记录,但仍需推送给区域运营和线上运营");
break; // 即使没有关注记录,也需要为每个门店 + 业务生成推送(场景 3)
} // 构造临时的 follow 记录用于推送
List<MerchantBiFollow> tempFollows = new ArrayList<>();
yesterdayDataMap.forEach((merchantId, data) -> data.forEach((biz, list) -> list.forEach(item -> {
MerchantBiFollow tempFollow = new MerchantBiFollow();
tempFollow.setMerchantId(item.getMerchantId());
tempFollow.setBusinessType(item.getBiz().byteValue());
tempFollow.setMerchantName(item.getMerchantName());
tempFollows.add(tempFollow);
})));
follows = tempFollows;
}
log.info("需要处理的关注记录数:{}", follows.size());
log.info("开始处理第{}页数据,当前页记录数:{}", pageNum, follows.size()); Map<String, StoreSettingDTO> settingMap = new HashMap<>();
// 2. 批量查询优化:提取所有 merchantId 和 followId // 4. 提取所有 merchantId 和 followId
List<Integer> merchantIds = follows.stream() List<Integer> merchantIds = follows.stream()
.map(MerchantBiFollow::getMerchantId) .map(MerchantBiFollow::getMerchantId)
.filter(Objects::nonNull) .filter(Objects::nonNull)
...@@ -90,20 +104,20 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -90,20 +104,20 @@ public class MerchantBiDailyPushJob implements SimpleJob {
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
// 提取所有业务类型(同一页可能包含不同业务类型) // 提取所有业务类型
List<Byte> businessTypes = follows.stream() List<Byte> actualBusinessTypes = follows.stream()
.map(MerchantBiFollow::getBusinessType) .map(MerchantBiFollow::getBusinessType)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
// 3. 批量查询昨日动态数 (返回 Map<key:merchantId_businessType, count>) // 5. 批量查询昨日动态数 (返回 Map<key:merchantId_businessType, count>)
Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, businessTypes); Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, actualBusinessTypes);
// 4. 批量查询门店配置 (按业务类型对应的 scene 查询) // 6. 批量查询门店配置 (按业务类型对应的 scene 查询)
cacheMerchantSettingMap(settingMap, merchantIds, businessTypes); cacheMerchantSettingMap(settingMap, merchantIds, actualBusinessTypes);
// 5. 批量查询关注明细 (一次 SQL 查询,内存中分组) // 7. 批量查询关注明细 (一次 SQL 查询,内存中分组)
List<MerchantBiFollowDetail> allDetails = followDetailMapper.batchFindByFollowId(followIds); List<MerchantBiFollowDetail> allDetails = followDetailMapper.batchFindByFollowId(followIds);
Map<Integer, List<MerchantBiFollowDetail>> followersMap = new HashMap<>(); Map<Integer, List<MerchantBiFollowDetail>> followersMap = new HashMap<>();
if (allDetails != null && !allDetails.isEmpty()) { if (allDetails != null && !allDetails.isEmpty()) {
...@@ -113,17 +127,20 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -113,17 +127,20 @@ public class MerchantBiDailyPushJob implements SimpleJob {
} }
log.info("followersMap:{}", followersMap); log.info("followersMap:{}", followersMap);
// 6. 内存匹配并推送 // 8. 内存匹配并推送
for (MerchantBiFollow follow : follows) { for (MerchantBiFollow follow : follows) {
try { try {
Integer merchantId = follow.getMerchantId(); Integer merchantId = follow.getMerchantId();
Integer followId = follow.getId(); Integer followId = follow.getId();
Byte businessType = follow.getBusinessType(); Byte businessType = follow.getBusinessType();
// 从 Map 中获取数据,避免循环查库 // 从 Map 中获取该门店 + 业务昨日的动态数
String countKey = merchantId + "_" + businessType; String countKey = merchantId + "_" + businessType;
Integer yesterdayCount = countMap.getOrDefault(countKey, 0); Integer yesterdayCount = countMap.getOrDefault(countKey, 0);
// 只推送昨日有动态的组合
if (yesterdayCount <= 0) { if (yesterdayCount <= 0) {
log.info("【{}-{}】门店昨日无动态", merchantId, businessType);
continue; continue;
} }
...@@ -136,16 +153,16 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -136,16 +153,16 @@ public class MerchantBiDailyPushJob implements SimpleJob {
} }
List<MerchantBiFollowDetail> details = followersMap.get(followId); List<MerchantBiFollowDetail> details = followersMap.get(followId);
if (details == null || details.isEmpty()) {
log.info("【{}-{}】门店无关注人,id:{}", merchantId, businessType, followId);
continue;
}
// 推送给负责人 (区域运营、线上运营) // 场景 3: 推送给区域运营和线上运营(无论是否有关注人都要推送)
pushToOperatorsWithData(follow, yesterdayCount, setting); pushToOperatorsWithData(follow, yesterdayCount, setting);
// 推送给所有关注人 // 场景 4: 推送给所有关注人(只有存在关注人才推送)
if (details != null && !details.isEmpty()) {
pushToFollowersWithDetails(follow, yesterdayCount, details); pushToFollowersWithDetails(follow, yesterdayCount, details);
} else {
log.info("【{}-{}】门店无关注人,仅推送给区域运营和线上运营", merchantId, businessType);
}
} catch (Exception e) { } catch (Exception e) {
log.error("处理门店关注记录失败,门店 ID:{}, 业务类型:{}, 错误:{}", log.error("处理门店关注记录失败,门店 ID:{}, 业务类型:{}, 错误:{}",
...@@ -153,14 +170,7 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -153,14 +170,7 @@ public class MerchantBiDailyPushJob implements SimpleJob {
} }
} }
// 7. 判断是否还有下一页 log.info("每日 BI 动态汇总推送任务执行完成");
if (!pageInfo.isHasNextPage()) {
log.info("数据处理完成,共处理{}页,总记录数:{}", pageInfo.getPages(), pageInfo.getTotal());
break;
}
pageNum++;
}
} }
/** /**
...@@ -169,7 +179,7 @@ public class MerchantBiDailyPushJob implements SimpleJob { ...@@ -169,7 +179,7 @@ public class MerchantBiDailyPushJob implements SimpleJob {
private void cacheMerchantSettingMap(Map<String, StoreSettingDTO> settingMap, List<Integer> merchantIds, List<Byte> businessTypes) { private void cacheMerchantSettingMap(Map<String, StoreSettingDTO> settingMap, List<Integer> merchantIds, List<Byte> businessTypes) {
for (Byte bizType : businessTypes) { for (Byte bizType : businessTypes) {
List<Integer> unCacheMerchantIds = new ArrayList<>(); List<Integer> unCacheMerchantIds = new ArrayList<>();
for (Integer merchantId : merchantIds){ for (Integer merchantId : merchantIds) {
String key = merchantId + "_" + bizType; String key = merchantId + "_" + bizType;
if (settingMap.containsKey(key)) { if (settingMap.containsKey(key)) {
continue; continue;
......
...@@ -37,4 +37,15 @@ public interface StrategyInfoMapper extends OreMapper<StrategyInfo> { ...@@ -37,4 +37,15 @@ public interface StrategyInfoMapper extends OreMapper<StrategyInfo> {
@Param("biz") Integer biz, @Param("biz") Integer biz,
@Param("startDate") Date startDate, @Param("startDate") Date startDate,
@Param("endDate") Date endDate); @Param("endDate") Date endDate);
/**
* 查询指定时间段内有新增策略/留言的门店 ID 列表
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return List<Map>, 每个 Map 包含 merchant_id
*/
List<StrategyInfo> findMerchantIdsWithCommentsByTime(
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
} }
...@@ -229,4 +229,17 @@ public class MerchantBiCommentService { ...@@ -229,4 +229,17 @@ public class MerchantBiCommentService {
merchantIds.size(), finalResult, System.currentTimeMillis() - startMs); merchantIds.size(), finalResult, System.currentTimeMillis() - startMs);
return finalResult; return finalResult;
} }
/**
* 查询昨日有新增策略/留言的门店
*/
public List<StrategyInfo> findMerchantIdsWithYesterdayComments() {
Date yesterdayStart = DateUtil.beginOfDay(DateUtil.yesterday());
Date yesterdayEnd = DateUtil.endOfDay(DateUtil.yesterday());
return strategyInfoMapper.findMerchantIdsWithCommentsByTime(
yesterdayStart,
yesterdayEnd
);
}
} }
...@@ -93,4 +93,13 @@ ...@@ -93,4 +93,13 @@
AND created_date BETWEEN #{startDate} AND #{endDate} AND created_date BETWEEN #{startDate} AND #{endDate}
GROUP BY merchant_id GROUP BY merchant_id
</select> </select>
<select id="findMerchantIdsWithCommentsByTime" resultMap="BaseResultMap">
SELECT
merchant_id, biz, merchant_name
FROM dj_smartcarlife.dj_car_life_strategy_info
WHERE deleted_flag = 'N'
AND created_date BETWEEN #{startDate} AND #{endDate}
ORDER BY merchant_id, biz
</select>
</mapper> </mapper>
  • @wangxw1
    commented
    Master

    一、关键问题与优化建议(Top 3)

    1. SQL 缺少聚合/去重,存在严重的内存溢出(OOM)与性能风险(重要性:高)

    • 问题描述:在 StrategyInfoMapper.xml 的 findMerchantIdsWithCommentsByTime 查询中,未对结果进行 GROUP BY 或 DISTINCT 处理。但在 MerchantBiDailyPushJob 第 63 行,Java 代码却将查出的全量数据按 merchantId 和 biz 进行内存分组。
    • 影响分析:如果某个门店在昨日有上千条策略/留言,该 SQL 会将这上千条明细全部查出并加载到 JVM 内存中,不仅造成极大的网络 I/O 浪费,在业务量大时极易引发 OOM。实际上业务只需要知道“哪些门店+业务有动态”。
    • 优化建议:将去重逻辑下推到数据库层,修改 XML 中的 SQL: xml <select id="findMerchantIdsWithCommentsByTime" resultMap="BaseResultMap"> SELECT merchant_id, biz, merchant_name FROM dj_smartcarlife.dj_car_life_strategy_info WHERE deleted_flag = 'N' AND created_date BETWEEN #{startDate} AND #{endDate} GROUP BY merchant_id, biz, merchant_name </select>

    2. MyBatis IN 查询传入空集合可能导致 SQL 语法异常(重要性:高)

    • 问题描述:在 MerchantBiDailyPushJob 第 78 行,如果所有有动态的门店都没有关注记录,代码会构造 tempFollows(此时 id 为 null)。这会导致第 98 行提取出的 followIds 为空集合。随后在第 112 行直接调用 followDetailMapper.batchFindByFollowId(followIds)。
    • 影响分析:如果 followIds 为空,MyBatis 默认会生成形如 SELECT ... WHERE follow_id IN () 的 SQL,这在 MySQL 中是语法错误(BadSqlGrammarException),会导致整个定时任务执行失败崩溃。
    • 优化建议:在执行批量查询前,必须对集合判空: java List<MerchantBiFollowDetail> allDetails = new ArrayList<>(); if (CollectionUtils.isNotEmpty(followIds)) { allDetails = followDetailMapper.batchFindByFollowId(followIds); }

    3. IN 语句参数数量无上限,存在数据库性能与稳定性隐患(重要性:中)

    • 问题描述:在 MerchantBiDailyPushJob 第 75 行,followMapper.findByMerchantIdsAndBiz(activeMerchantIds, null) 直接将 activeMerchantIds 传入 SQL 的 IN 条件中。
    • 影响分析:activeMerchantIds 的大小取决于昨日活跃的门店数量。如果数量达到数千个,超长的 IN 列表会导致 MySQL 解析变慢,无法有效利用索引(受限于 eq_range_index_dive_limit),甚至突破 max_allowed_packet 限制导致查询失败。
    • 优化建议:使用工具类(如 Guava 的 Lists.partition 或 Hutool 的 ListUtil.split)将大集合进行分片,分批次查询并合并结果: java List<MerchantBiFollow> follows = new ArrayList<>(); // 假设每批处理 500 个 List<List<Integer>> partitions = Lists.partition(activeMerchantIds, 500); for (List<Integer> partition : partitions) { follows.addAll(followMapper.findByMerchantIdsAndBiz(partition, null)); }

    二、评分明细

    • 功能实现的正确性与健壮性(32/40分): 核心业务逻辑(改为按变动门店驱动推送)方向正确,有效避免了全表扫描。但扣分在于健壮性不足:构造临时对象导致的主键为 null,进而引发下游 MyBatis IN 查询传入空集合的潜在崩溃风险。
    • 安全性与潜在风险(30/30分): 未见 SQL 注入、越权等安全漏洞,日志中未打印敏感的个人隐私信息,符合安全规范。
    • 最佳实践与可维护性(16/20分): 代码结构清晰,注释详尽,可读性较好。扣分点在于为了复用后续的推送逻辑,强行构造了带有 null 属性的 "Fake Entity" (tempFollow) 混入正常集合,这在面向对象设计中是一种代码坏味道(Code Smell),容易给后续维护者造成困扰。
    • 性能与资源利用(2/5分): 扣分较多。将原本应该由数据库承担的去重工作(GROUP BY)放到了 Java 内存中进行,且未对长列表 IN 查询进行分片控制,在数据量上涨时存在明显的性能瓶颈。
    • 提交信息质量(5/5分): Commit message 非常优秀,采用了清晰的列表形式,准确描述了“为什么改”、“改了什么”以及“带来的收益”,完全符合工程最佳实践。

    总分:85分

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