Commit 22d48f18 by 林永健

refactor(push): 优化门店配置信息缓存及关注人推送逻辑

- 合并并优化门店配置信息缓存方法,减少重复查询
- 使用 MerchantBasicInfoService 过滤区域运营和线上运营人员 UUID
- MerchantBasicInfoService 新增根据角色过滤员工 UUID 的方法
- 关注列表接口维护当前员工关注状态标记
- 修正推送名单获取逻辑,整合运营人员推送目标UUID集合
- 移除多余的业务类型名称方法,统一格式化策略留言显示文本
- 业务场景分析服务中调整产值权限过滤调用顺序,避免异常影响处理
- Mapper 中修改关注记录查询分组字段,优化数据库查询逻辑
1 parent bd5b2675
package cn.com.glsx.dj.peanalysis.job;
import cn.com.glsx.dj.peanalysis.dto.analysis.MerchantBiCommentReq;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
import cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowDetailMapper;
import cn.com.glsx.dj.peanalysis.mapper.MerchantBiFollowMapper;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollow;
import cn.com.glsx.dj.peanalysis.model.MerchantBiFollowDetail;
import cn.com.glsx.dj.peanalysis.service.MerchantBasicInfoService;
import cn.com.glsx.dj.peanalysis.service.MerchantBiCommentService;
import cn.com.glsx.dj.peanalysis.service.WechatPushService;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
import cn.com.glsx.dj.peanalysis.utils.MetricsValueUtils;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
......@@ -18,6 +18,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
......@@ -49,6 +50,9 @@ public class MerchantBiDailyPushJob implements SimpleJob {
@Resource
private ServiceMerchantMapper serviceMerchantMapper;
@Autowired
private MerchantBasicInfoService merchantBasicInfoService;
@Override
public void execute(ShardingContext shardingContext) {
log.info("开始执行每日 BI 动态汇总推送任务");
......@@ -56,7 +60,8 @@ public class MerchantBiDailyPushJob implements SimpleJob {
// 1. 分页获取所有存在关注的门店 + 业务组合
int pageNum = 1;
int pageSize = 500; // 每页处理 500 条记录
Map<String, StoreSettingDTO> settingMap = new HashMap<>();
while (true) {
// 使用 PageHelper 进行分页查询
PageHelper.startPage(pageNum, pageSize);
......@@ -96,20 +101,8 @@ public class MerchantBiDailyPushJob implements SimpleJob {
Map<String, Integer> countMap = commentService.batchCountYesterdayCommentsByBizType(merchantIds, businessTypes);
// 4. 批量查询门店配置 (按业务类型对应的 scene 查询)
Map<String, StoreSettingDTO> settingMap = new HashMap<>();
for (Byte bizType : businessTypes) {
Integer scene = MetricsValueUtils.convertBizsToScene(bizType.intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(merchantIds, scene);
for (StoreSettingDTO setting : settings) {
if (setting != null && setting.getMerchantId() != null) {
// key: merchantId_bizType
String key = setting.getMerchantId() + "_" + bizType;
settingMap.put(key, setting);
}
}
}
log.info("settingMap:{}", settingMap);
cacheMerchantSettingMap(settingMap, merchantIds, businessTypes);
// 5. 批量查询关注明细 (一次 SQL 查询,内存中分组)
List<MerchantBiFollowDetail> allDetails = followDetailMapper.batchFindByFollowId(followIds);
Map<Integer, List<MerchantBiFollowDetail>> followersMap = new HashMap<>();
......@@ -171,6 +164,41 @@ public class MerchantBiDailyPushJob implements SimpleJob {
}
/**
* 处理业务+门店下的配置信息缓存
*/
private void cacheMerchantSettingMap(Map<String, StoreSettingDTO> settingMap, List<Integer> merchantIds, List<Byte> businessTypes) {
for (Byte bizType : businessTypes) {
List<Integer> unCacheMerchantIds = new ArrayList<>();
for (Integer merchantId : merchantIds){
String key = merchantId + "_" + bizType;
if (settingMap.containsKey(key)) {
continue;
}
unCacheMerchantIds.add(merchantId);
}
if (CollectionUtils.isEmpty(unCacheMerchantIds)) {
continue;
}
Integer scene = MetricsValueUtils.convertBizsToScene(bizType.intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(unCacheMerchantIds, scene);
for (StoreSettingDTO setting : settings) {
if (setting == null || setting.getMerchantId() == null) {
continue;
}
String key = setting.getMerchantId() + "_" + bizType;
// 处理区域运营和线上运营人员,重新赋值
setting.setRegionalOperationId(String.join(",", merchantBasicInfoService.getOperationStaffUuid(setting)));
setting.setOnlineOperationId(String.join(",", merchantBasicInfoService.getOnlineStaffUuid(setting)));
settingMap.put(key, setting);
}
}
log.info("settingMap.keySet:{}", settingMap.keySet());
}
/**
* 推送给负责人(使用已查询的配置数据)
*/
private void pushToOperatorsWithData(MerchantBiFollow follow, int count, StoreSettingDTO setting) {
......@@ -178,6 +206,7 @@ public class MerchantBiDailyPushJob implements SimpleJob {
Byte businessType = follow.getBusinessType();
List<String> targetUuids = new ArrayList<>();
// 此时的uuid已经经过角色有效性过滤
if (StringUtils.isNotBlank(setting.getRegionalOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ",")));
if (StringUtils.isNotBlank(setting.getOnlineOperationId()))
......@@ -212,61 +241,4 @@ public class MerchantBiDailyPushJob implements SimpleJob {
wechatPushService.pushDailySummaryMsg(follow, count, followerUuids, true);
}
private void pushToOperators(MerchantBiFollow follow, int count) {
Integer merchantId = follow.getMerchantId();
Byte businessType = follow.getBusinessType();
Integer scene = MetricsValueUtils.convertBizsToScene(businessType.intValue());
List<StoreSettingDTO> settings = serviceMerchantMapper.findStoreSetting(Collections.singletonList(follow.getMerchantId()), scene);
if (CollectionUtils.isEmpty(settings)) {
log.info("【{}-{}】门店无相关配置", merchantId, businessType);
return;
}
StoreSettingDTO setting = settings.get(0);
List<String> targetUuids = new ArrayList<>();
if (StringUtils.isNotBlank(setting.getRegionalOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ",")));
if (StringUtils.isNotBlank(setting.getOnlineOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getOnlineOperationId(), ",")));
if (CollectionUtils.isEmpty(targetUuids)) {
log.info("【{}-{}】门店配置无相应人员", merchantId, businessType);
return;
}
wechatPushService.pushDailySummaryMsg(follow, count, targetUuids, false);
}
private void pushToFollowers(MerchantBiFollow follow, int count) {
List<MerchantBiFollowDetail> details = followDetailMapper.findByFollowId(follow.getId());
if (CollectionUtils.isEmpty(details)) {
log.info("【{}-{}】门店无关注人, id:{}", follow.getMerchantId(), follow.getBusinessType(), follow.getId());
return;
}
List<String> followerUuids = details.stream()
.map(MerchantBiFollowDetail::getStaffUuid)
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(followerUuids)) {
log.info("【{}-{}】门店无关注人, id:{}", follow.getMerchantId(), follow.getBusinessType(), follow.getId());
return;
}
wechatPushService.pushDailySummaryMsg(follow, count, followerUuids, true);
}
private String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
}
......@@ -1640,11 +1640,6 @@ public class BusinessSceneAnalysisService {
StoreDetailSummaryResponse res = new StoreDetailSummaryResponse();
DataBizQueryParamsDTO queryParams = req.convertQueryParam();
long startMs = System.currentTimeMillis();
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
} catch (Exception e) {
return res;
}
// 查询门店信息:所属服务商、区域运营、销售、线上运营
Integer sceneType = req.convertToSceneType(queryParams.getBizs());
......@@ -1667,6 +1662,13 @@ public class BusinessSceneAnalysisService {
MerchantBasicInfoListResponse merchantInfo = merchantBasicInfoService.queryMerchantBasicInfo(req.getMerchantIds().get(0));
merchantBasicInfoService.fillStoreDetailTechnicianSupervisor(res, merchantInfo, req.getBizs());
// 产值权限过滤
try {
req.setMerchantIds(getMerchantIdPermission(req, false));
} catch (Exception e) {
return res;
}
// 查询指标
queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
List<String> itemCodes = Lists.newArrayList(DataStatsConstants.ITEM_CODE_A036, DataStatsConstants.ITEM_CODE_A062,
......
package cn.com.glsx.dj.peanalysis.service;
import cn.com.glsx.dj.peanalysis.dto.StoreSettingDTO;
import cn.com.glsx.dj.peanalysis.dto.res.output.MyFollowResponse;
import cn.com.glsx.dj.peanalysis.dto.res.output.StoreDetailSummaryResponse;
import cn.com.glsx.dj.peanalysis.mapper.ServiceMerchantMapper;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.merchants.dto.merchant.CarbrandResponse;
import cn.com.glsx.merchants.model.request.MerchantStaffRequest;
import cn.com.glsx.merchants.model.request.merchant.MerchantBasicInfoRequest;
import cn.com.glsx.merchants.model.request.merchant.MerchantInfoSwitch;
import cn.com.glsx.merchants.model.response.MerchantStaffResponse;
import cn.com.glsx.merchants.model.response.merchant.MerchantBasicInfoListResponse;
import cn.com.glsx.merchants.remote.MerchantRemote;
import cn.com.glsx.merchants.remote.MerchantStaffRemote;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.*;
......@@ -27,8 +32,14 @@ public class MerchantBasicInfoService {
private MerchantRemote merchantRemote;
@Autowired
private MerchantStaffRemote merchantStaffRemote;
@Autowired
private ServiceMerchantMapper serviceMerchantMapper;
@Autowired
private Environment environment;
/**
* 批量查询门店基础信息(省/市/主营品牌等),返回 Map<merchantId, info>
*/
......@@ -180,4 +191,67 @@ public class MerchantBasicInfoService {
res.setTechnicianSupervisor(supervisorName);
}
}
/**
* 指定员工uuid和角色查询员工uuid
*/
public List<String> getStaffUuidWithRole(List<String> uuids, String roleName) {
MerchantStaffRequest req = new MerchantStaffRequest();
req.setStaffUuidList(uuids);
req.setRoleName(roleName);
RpcResponse<List<MerchantStaffResponse>> staffListRemote = merchantStaffRemote.findMerchantStaffListRemote(req);
if (staffListRemote.isFailed()) {
log.error("查询账户中心员工异常, req={}, res={}", req, staffListRemote);
return null;
}
List<MerchantStaffResponse> staffList = staffListRemote.getResult();
if (CollectionUtils.isEmpty(staffList)) {
log.warn("查询账户中心员工为空, req={}, res={}", req, staffListRemote);
return Collections.emptyList();
}
List<String> res = staffList.stream().map(MerchantStaffResponse::getUuid).collect(Collectors.toList());
log.info("原始uuid:{},【{}】结果:{},排除:{}", uuids, roleName, res, CollectionUtils.subtract(uuids, res));
return res;
}
/**
* 指定门店配置,查询相关区域运营员工uuid
*/
public Collection<String> getOperationStaffUuid(StoreSettingDTO setting) {
if (setting == null) {
return Collections.emptyList();
}
if (StringUtils.isBlank(setting.getRegionalOperationId())) {
return Collections.emptyList();
}
List<String> configUuids = Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ","));
if (CollectionUtils.isEmpty(configUuids)) {
return Collections.emptyList();
}
// 查询账户中心员工角色是否正确,过滤过期数据
String roleName = environment.getProperty("dj.pe.analysis.push.regional.operation.role", "区域运营");
List<String> uuids = getStaffUuidWithRole(configUuids, roleName);
return uuids;
}
/**
* 指定门店配置,查询相关区域运营员工uuid
*/
public Collection<String> getOnlineStaffUuid(StoreSettingDTO setting) {
if (setting == null) {
return Collections.emptyList();
}
if (StringUtils.isBlank(setting.getOnlineOperationId())) {
return Collections.emptyList();
}
List<String> configUuids = Arrays.asList(StringUtils.split(setting.getOnlineOperationId(), ","));
if (CollectionUtils.isEmpty(configUuids)) {
return Collections.emptyList();
}
// 查询账户中心员工角色是否正确,过滤过期数据
String roleName = environment.getProperty("dj.pe.analysis.push.online.operation.role", "线上运营");
List<String> uuids = getStaffUuidWithRole(configUuids, roleName);
return uuids;
}
}
......@@ -229,18 +229,4 @@ public class MerchantBiCommentService {
merchantIds.size(), finalResult, System.currentTimeMillis() - startMs);
return finalResult;
}
private String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
}
......@@ -201,6 +201,21 @@ public class MerchantBiFollowService {
return Collections.emptyList();
}
// 维护当前员工的关注状态
List<MyFollowResponse> myFollowList = followMapper.findMyFollowsByStaffUuid(req.getLoginUserUuid(), req.getMerchantName());
if (CollectionUtils.isNotEmpty(myFollowList)) {
List<String> myFollowItems = myFollowList.stream()
.map(p -> p.getMerchantId() + "_" + p.getBusinessType())
.distinct()
.collect(Collectors.toList());
resList.forEach(p -> {
String key = p.getMerchantId() + "_" + p.getBusinessType();
if (myFollowItems.contains(key)) {
p.setIsFollow(1);
}
});
}
log.info("查询他人关注列表:开始填充扩展信息,loginUserUuid={}, 关注条数={}", req.getLoginUserUuid(), resList.size());
fillFollowDetails(resList, req);
......@@ -323,7 +338,7 @@ public class MerchantBiFollowService {
if (latestStrategies != null) {
latestStrategies.forEach((mid, strategy) -> {
String timeAgo = DateUtils.formatTimeAgo(strategy.getCreatedDate());
latestCommentMap.put(mid + "_" + biz, String.format("「%s」,「%s」已添加跟进策略(留言)", timeAgo, strategy.getCreatedBy()));
latestCommentMap.put(mid + "_" + biz, String.format("%s,%s已添加跟进策略(留言)", timeAgo, strategy.getCreatedBy()));
latestStrategyIdMap.put(mid + "_" + biz, strategy.getId());
});
}
......@@ -424,7 +439,7 @@ public class MerchantBiFollowService {
return;
}
String timeAgo = DateUtils.formatTimeAgo(summary.getCreatedDate());
item.setLatestComment(String.format("「%s」,「%s」已添加跟进策略(留言)", timeAgo, summary.getCreatedBy()));
item.setLatestComment(String.format("%s,%s已添加跟进策略(留言)", timeAgo, summary.getCreatedBy()));
});
log.info("门店列表填充关注信息完成:biz={}, 门店数={}, costMs={}", businessType, merchantIds.size(), System.currentTimeMillis() - startMs);
......@@ -629,10 +644,8 @@ public class MerchantBiFollowService {
}
StoreSettingDTO setting = settings.get(0);
List<String> targetUuids = new ArrayList<>();
if (StringUtils.isNotBlank(setting.getRegionalOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getRegionalOperationId(), ",")));
if (StringUtils.isNotBlank(setting.getOnlineOperationId()))
targetUuids.addAll(Arrays.asList(StringUtils.split(setting.getOnlineOperationId(), ",")));
targetUuids.addAll(merchantBasicInfoService.getOperationStaffUuid(setting));
targetUuids.addAll(merchantBasicInfoService.getOnlineStaffUuid(setting));
if (CollectionUtils.isEmpty(targetUuids)) {
log.info("触发关注推送:未找到推送目标,merchantId={}, biz={}", request.getMerchantId(), request.getBusinessType());
return;
......@@ -645,20 +658,6 @@ public class MerchantBiFollowService {
}
}
private String getBusinessTypeName(Byte businessType) {
if (businessType == null) return "未知业务";
switch (businessType) {
case 1:
return "延保";
case 2:
return "轻改";
case 3:
return "权益";
default:
return "未知业务";
}
}
private MerchantBiFollow getOrCreateFollow(MerchantBiFollowReq request) {
MerchantBiFollow follow = followMapper.findFollowByMerchantAndBiz(request.getMerchantId(), request.getBusinessType());
......
......@@ -84,7 +84,7 @@
<if test="req != null and req.merchantName != null and req.merchantName != ''">
AND f.merchant_name LIKE CONCAT('%', #{req.merchantName}, '%')
</if>
GROUP BY f.merchant_id, f.merchant_name, f.business_type
GROUP BY f.merchant_id, f.business_type
ORDER BY followDate DESC
</select>
......
  • @wangxw1
    commented
    Master

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

    1. 潜在的空指针异常(NPE)风险,将导致定时任务崩溃(重要性:高)

    • 问题描述:在 MerchantBasicInfoService.java 的 getStaffUuidWithRole 方法中,当 RPC 调用失败时返回了 null。该返回值会逐层传递给 MerchantBiDailyPushJob.java 中的 cacheMerchantSettingMap 方法,并执行 String.join(",", merchantBasicInfoService.getOperationStaffUuid(setting))。由于 String.join 方法的第二个参数如果传入 null 会直接抛出 NullPointerException,这将导致整个每日推送定时任务(Job)中断。
    • 影响分析:RPC 偶发超时或失败是常见现象,一旦发生将引发未捕获的 NPE,导致当批次及后续的门店数据无法完成推送,系统健壮性较差。
    • 优化建议:防御性编程,RPC 失败时应返回空集合而不是 null。 java // MerchantBasicInfoService.java 中修改: if (staffListRemote.isFailed()) { log.error("查询账户中心员工异常, req={}, res={}", req, staffListRemote); return Collections.emptyList(); // 将 return null 改为返回空集合 }

    2. 循环内执行 RPC 调用引发严重的 N+1 性能瓶颈(重要性:高)

    • 问题描述:在 MerchantBiDailyPushJob.java 的 cacheMerchantSettingMap 方法中,遍历 settings 列表时,对每个 setting 都调用了 getOperationStaffUuid 和 getOnlineStaffUuid。这两个方法底层均会发起 merchantStaffRemote.findMerchantStaffListRemote RPC 调用。
    • 影响分析:该定时任务设定每页处理 500 条记录,这意味着在一个分页批次中可能会发起上百次甚至上千次同步 RPC 请求。这不仅会极大拖慢任务执行速度,还可能耗尽 RPC 线程池,对下游账户中心服务造成瞬间的流量冲击并引发超时。
    • 优化建议:将循环内的 RPC 调用改为批量处理。先遍历一遍 settings 收集所有需要校验的员工 UUID 集合,发起一次 RPC 批量查询后,将其转为 Map<String, Role> 缓存在本地,再进行第二次遍历赋值。

    3. 嵌套循环中的 List.contains 查询导致 O(N*M) 复杂度(重要性:中)

    • 问题描述:在 MerchantBiFollowService.java 的 findOthersFollows 方法中,提取了 myFollowItems 作为 List<String>。随后在 resList.forEach 循环中使用了 myFollowItems.contains(key) 来判断是否关注。
    • 影响分析:List 的 contains 方法时间复杂度为 O(N),嵌套在循环中会导致整体时间复杂度变为 O(N*M)。虽然目前数据量可能不大,但属于典型的数据结构误用,不符合最佳实践。
    • 优化建议:将 List 替换为 Set,利用 Hash 结构将判断复杂度降为 O(1)。 java // MerchantBiFollowService.java Set<String> myFollowItems = myFollowList.stream() .map(p -> p.getMerchantId() + "_" + p.getBusinessType()) .collect(Collectors.toSet()); // 去掉 distinct(),直接使用 toSet()

    二、评分明细

    • 功能实现的正确性与健壮性(32/40分):重构了推送逻辑并整合了冗余代码,整体业务逻辑方向正确。但未能妥善处理 RPC 异常场景下的返回值,存在引发定时任务崩溃的致命 NPE 隐患(扣除 8 分)。
    • 安全性与潜在风险(30/30分):代码变更未引入越权、SQL 注入等明显的安全漏洞,未发现 MyBatis 禁用子查询的违规情况。
    • 最佳实践与可维护性(16/20分):有效地清理了多处重复的 getBusinessTypeName 代码,提升了可维护性。但集合类型选择不当(List 替代 Set),且存在返回 null 替代空集合的坏味道(扣除 4 分)。
    • 性能与资源利用(2/5分):在批处理定时任务的 for 循环中直接发起 RPC 同步调用,是严重的性能反模式,会造成大量的网络开销和潜在的服务雪崩风险(扣除 3 分)。
    • 提交信息质量(5/5分):Commit message 格式规范,清晰地分条列出了优化点和重构内容,便于后续追溯和 Code Review。

    总分:85分

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