Commit a0ca291c by chenxi

修复bug,新增、编辑sku一码一名校验逻辑改动,排除掉自身。

修改产品适用区域后,下架商品逻辑因死锁导致失败,增加事务提交后执行
1 parent c8b8fe1f
...@@ -166,14 +166,18 @@ public class ProductTemplateService { ...@@ -166,14 +166,18 @@ public class ProductTemplateService {
* *
* @param productName 产品名称 * @param productName 产品名称
* @param productCode 产品编码 * @param productCode 产品编码
* @param excludeId 排除自身ID(编辑时传入,新增传null)
*/ */
public void checkUpgradeGoodsUnique(String productName, String productCode) { public void checkUpgradeGoodsUnique(String productName, String productCode, Integer excludeId) {
// 1. 按名称+编码组合精确匹配,已存在则视为合法,无需校验 // 1. 按名称+编码组合精确匹配,已存在则视为合法,无需校验
Example matchExample = new Example(UpgradeGoods.class); Example matchExample = new Example(UpgradeGoods.class);
matchExample.createCriteria() Example.Criteria matchCriteria = matchExample.createCriteria()
.andEqualTo("upgradeGoodsName", productName) .andEqualTo("upgradeGoodsName", productName)
.andEqualTo("type", productCode) .andEqualTo("type", productCode)
.andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name()); .andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name());
if (excludeId != null) {
matchCriteria.andNotEqualTo("id", excludeId);
}
List<UpgradeGoods> matchList = upgradeGoodsMapper.selectByExample(matchExample); List<UpgradeGoods> matchList = upgradeGoodsMapper.selectByExample(matchExample);
if (matchList != null && !matchList.isEmpty()) { if (matchList != null && !matchList.isEmpty()) {
return; return;
...@@ -181,9 +185,12 @@ public class ProductTemplateService { ...@@ -181,9 +185,12 @@ public class ProductTemplateService {
// 2. 校验 productName 是否重复(对应 upgrade_goods_name) // 2. 校验 productName 是否重复(对应 upgrade_goods_name)
Example nameExample = new Example(UpgradeGoods.class); Example nameExample = new Example(UpgradeGoods.class);
nameExample.createCriteria() Example.Criteria nameCriteria = nameExample.createCriteria()
.andEqualTo("upgradeGoodsName", productName) .andEqualTo("upgradeGoodsName", productName)
.andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name()); .andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name());
if (excludeId != null) {
nameCriteria.andNotEqualTo("id", excludeId);
}
List<UpgradeGoods> nameList = upgradeGoodsMapper.selectByExample(nameExample); List<UpgradeGoods> nameList = upgradeGoodsMapper.selectByExample(nameExample);
if (nameList != null && !nameList.isEmpty()) { if (nameList != null && !nameList.isEmpty()) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
...@@ -192,9 +199,12 @@ public class ProductTemplateService { ...@@ -192,9 +199,12 @@ public class ProductTemplateService {
// 3. 校验 productCode 是否重复(对应 type) // 3. 校验 productCode 是否重复(对应 type)
Example codeExample = new Example(UpgradeGoods.class); Example codeExample = new Example(UpgradeGoods.class);
codeExample.createCriteria() Example.Criteria codeCriteria = codeExample.createCriteria()
.andEqualTo("type", productCode) .andEqualTo("type", productCode)
.andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name()); .andEqualTo("deletedFlag", BaseModel.DeletedFlagEnum.N.name());
if (excludeId != null) {
codeCriteria.andNotEqualTo("id", excludeId);
}
List<UpgradeGoods> codeList = upgradeGoodsMapper.selectByExample(codeExample); List<UpgradeGoods> codeList = upgradeGoodsMapper.selectByExample(codeExample);
if (codeList != null && !codeList.isEmpty()) { if (codeList != null && !codeList.isEmpty()) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
......
...@@ -377,44 +377,47 @@ public class UpgradeGoodsService { ...@@ -377,44 +377,47 @@ public class UpgradeGoodsService {
* @param newProductAreaList 产品变更后的新适用区域列表 * @param newProductAreaList 产品变更后的新适用区域列表
* @param updatedBy 操作人 * @param updatedBy 操作人
*/ */
private void checkAndOffShelfByAreaChange( @Transactional(propagation=Propagation.REQUIRED, rollbackFor=RpcServiceException.class)
Integer upgradeGoodsId, public void checkAndOffShelfByAreaChange(Integer upgradeGoodsId, List<UpgradeGoodsArea> newProductAreaList, String updatedBy) {
List<UpgradeGoodsArea> newProductAreaList, TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
String updatedBy) { @Override
taskExecutor.execute(() -> { public void afterCommit() {
try { taskExecutor.execute(() -> {
log.info("checkAndOffShelfByAreaChange start, upgradeGoodsId:{}, updatedBy:{}", upgradeGoodsId, updatedBy); try {
// step1: 产品新区域含全国(-1),直接返回 log.info("checkAndOffShelfByAreaChange start, upgradeGoodsId:{}, updatedBy:{}", upgradeGoodsId, updatedBy);
boolean isNational = newProductAreaList.stream() // step1: 产品新区域含全国(-1),直接返回
.anyMatch(a -> "-1".equals(a.getCityCode())); boolean isNational = newProductAreaList.stream()
if (isNational) { .anyMatch(a -> "-1".equals(a.getCityCode()));
log.info("checkAndOffShelfByAreaChange end, upgradeGoodsId:{}, updatedBy:{}, reason:新区域含全国", upgradeGoodsId, updatedBy); if (isNational) {
return; log.info("checkAndOffShelfByAreaChange end, upgradeGoodsId:{}, updatedBy:{}, reason:新区域含全国", upgradeGoodsId, updatedBy);
} return;
// step2: 提取产品新区域 cityCode 集合 }
Set<String> productCityCodes = newProductAreaList.stream() // step2: 提取产品新区域 cityCode 集合
.map(UpgradeGoodsArea::getCityCode) Set<String> productCityCodes = newProductAreaList.stream()
.collect(Collectors.toSet()); .map(UpgradeGoodsArea::getCityCode)
// step3: 查询该产品下所有上架的商品/套餐子商品记录 .collect(Collectors.toSet());
String offShelfUpdatedBy = updatedBy + "修改产品适用区域"; // step3: 查询该产品下所有上架的商品/套餐子商品记录
List<MerchantGoodsInfo> relatedGoodsList = merchantGoodsInfoService.listByCondition( String offShelfUpdatedBy = updatedBy + "修改产品适用区域";
MerchantGoodsInfoDTO.builder() List<MerchantGoodsInfo> relatedGoodsList = merchantGoodsInfoService.listByCondition(
.upgradeGoodsId(upgradeGoodsId) MerchantGoodsInfoDTO.builder()
.status(CarLifeEnum.MerchantGoodsStatus.ON_SHELF.getValue()) .upgradeGoodsId(upgradeGoodsId)
.deletedFlag(BaseModel.DeletedFlagEnum.N.name()) .status(CarLifeEnum.MerchantGoodsStatus.ON_SHELF.getValue())
.build()); .deletedFlag(BaseModel.DeletedFlagEnum.N.name())
if (CollectionUtils.isEmpty(relatedGoodsList)) { .build());
log.info("checkAndOffShelfByAreaChange end, upgradeGoodsId:{}, updatedBy:{}, reason:无相关商品", upgradeGoodsId, updatedBy); if (CollectionUtils.isEmpty(relatedGoodsList)) {
return; log.info("checkAndOffShelfByAreaChange end, upgradeGoodsId:{}, updatedBy:{}, reason:无相关商品", upgradeGoodsId, updatedBy);
} return;
// step4: 处理普通商品 }
offShelfMerchantGoods(relatedGoodsList, productCityCodes, offShelfUpdatedBy); // step4: 处理普通商品
// step5: 处理套餐(packageCode 去重) offShelfMerchantGoods(relatedGoodsList, productCityCodes, offShelfUpdatedBy);
offShelfMerchantPackages(relatedGoodsList, productCityCodes, offShelfUpdatedBy); // step5: 处理套餐(packageCode 去重)
} catch (Exception e) { offShelfMerchantPackages(relatedGoodsList, productCityCodes, offShelfUpdatedBy);
log.warn("区域变更级联下架处理失败 upgradeGoodsId={}", upgradeGoodsId, e); } catch (Exception e) {
} log.warn("区域变更级联下架处理失败 upgradeGoodsId={}", upgradeGoodsId, e);
}); }
});
}
});
} }
/** /**
...@@ -765,27 +768,12 @@ public class UpgradeGoodsService { ...@@ -765,27 +768,12 @@ public class UpgradeGoodsService {
if (upgradeGoods != null) { if (upgradeGoods != null) {
toAddList.add(upgradeGoods); toAddList.add(upgradeGoods);
} }
// 同步产品清单
if (dto.getProductTemplateId() == null) { //一码一名校验
// 情况A:不带 productTemplateId,视为全新数据,校验名称和编码的唯一性 if (StringUtils.isNotBlank(dto.getUpgradeGoodsName()) && StringUtils.isNotBlank(dto.getType())) {
if (StringUtils.isNotBlank(dto.getUpgradeGoodsName()) && StringUtils.isNotBlank(dto.getType())) { productTemplateService.checkUpgradeGoodsUnique(dto.getUpgradeGoodsName(), dto.getType(), dto.getId());
productTemplateService.checkUpgradeGoodsUnique( }
dto.getUpgradeGoodsName(), dto.getType());
}
} else {
// 情况B/C:携带 productTemplateId,说明数据来自产品清单
// 查询清单当前名称/编码,判断是否发生变更
ProductTemplate productTemplate = productTemplateService.getById(dto.getProductTemplateId());
if (productTemplate != null) {
boolean nameChanged = !Objects.equals(dto.getUpgradeGoodsName(), productTemplate.getProductName());
boolean typeChanged = !Objects.equals(dto.getType(), productTemplate.getProductCode());
if (nameChanged || typeChanged) {
//此时不允许改动名称或者编码
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "不允许改动名称或者编码,请去产品清单中操作");
}
// 情况C:无变更,直接插入,无需额外操作
}
}
// 维护 onShelfStatus:scrm 来源下架,D+ 来源上架 // 维护 onShelfStatus:scrm 来源下架,D+ 来源上架
if (scrmSyncUpdate) { if (scrmSyncUpdate) {
upgradeGoods.setOnShelfStatus(ProductStatusEnum.OFF_SHELF.getCode()); upgradeGoods.setOnShelfStatus(ProductStatusEnum.OFF_SHELF.getCode());
...@@ -934,7 +922,8 @@ public class UpgradeGoodsService { ...@@ -934,7 +922,8 @@ public class UpgradeGoodsService {
public void updateUpgradeGoods(UpgradeGoodsDTO item, String updateBy, List<UpgradeGoodsDTO> oldUpgradeGoodsList) { public void updateUpgradeGoods(UpgradeGoodsDTO item, String updateBy, List<UpgradeGoodsDTO> oldUpgradeGoodsList) {
updateUpgradeGoods(item, updateBy, oldUpgradeGoodsList, false); updateUpgradeGoods(item, updateBy, oldUpgradeGoodsList, false);
} }
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=RpcServiceException.class)
public List<ProductNoticeEvent> updateUpgradeGoods(UpgradeGoodsDTO item, String updateBy, List<UpgradeGoodsDTO> oldUpgradeGoodsList, boolean scrmSyncUpdate) { public List<ProductNoticeEvent> updateUpgradeGoods(UpgradeGoodsDTO item, String updateBy, List<UpgradeGoodsDTO> oldUpgradeGoodsList, boolean scrmSyncUpdate) {
log.info("updateUpgradeGoods start, id:{}, updateBy:{}, scrmSyncUpdate:{}", item.getId(), updateBy, scrmSyncUpdate); log.info("updateUpgradeGoods start, id:{}, updateBy:{}, scrmSyncUpdate:{}", item.getId(), updateBy, scrmSyncUpdate);
List<ProductNoticeEvent> events = new ArrayList<>(); List<ProductNoticeEvent> events = new ArrayList<>();
...@@ -1003,7 +992,7 @@ public class UpgradeGoodsService { ...@@ -1003,7 +992,7 @@ public class UpgradeGoodsService {
// 情况A:不带 productTemplateId,视为全新数据,校验名称和编码的唯一性 // 情况A:不带 productTemplateId,视为全新数据,校验名称和编码的唯一性
if (StringUtils.isNotBlank(item.getUpgradeGoodsName()) && StringUtils.isNotBlank(item.getType())) { if (StringUtils.isNotBlank(item.getUpgradeGoodsName()) && StringUtils.isNotBlank(item.getType())) {
productTemplateService.checkUpgradeGoodsUnique( productTemplateService.checkUpgradeGoodsUnique(
item.getUpgradeGoodsName(), item.getType()); item.getUpgradeGoodsName(), item.getType(), item.getId());
} }
/*}*/ /*}*/
......
  • @wangxw1
    commented
    Master

    这是一份针对您提交代码的专业审查报告。本次审查重点关注了代码的功能正确性(特别是 Spring 事务机制的正确使用)、健壮性以及工程最佳实践。

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

    1. Spring AOP 代理失效导致 @Transactional 注解无法生效(功能正确性 - 高危)

    • 问题描述:在 UpgradeGoodsService.java 中,开发者为包含 4 个参数的 updateUpgradeGoods 方法添加了 @Transactional 注解。但该类中存在一个 3 个参数的重载方法,通过 this.updateUpgradeGoods(item, updateBy, oldUpgradeGoodsList, false); 内部调用了该目标方法。
    • 影响分析:由于 Spring AOP 的机制,类内部的方法调用(this.)会绕过代理对象,直接调用目标类的方法。这意味着当其他组件调用 3 个参数的 updateUpgradeGoods 时,4 个参数方法上的 @Transactional 注解将完全失效,发生异常时不会触发回滚,导致脏数据。同理,checkAndOffShelfByAreaChange 如果也是被类内部方法调用,其事务注解同样失效。
    • 优化建议: 将 @Transactional 注解提升到类外部调用的入口方法上,或者使用 AopContext.currentProxy() 获取代理对象进行调用。 java // 建议方案:在入口方法上加注解,或确保调用方已有事务 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public void updateUpgradeGoods(UpgradeGoodsDTO item, String updateBy, List<UpgradeGoodsDTO> oldUpgradeGoodsList) { // 内部调用,事务由当前入口方法接管 updateUpgradeGoods(item, updateBy, oldUpgradeGoodsList, false); }

    2. TransactionSynchronizationManager 存在抛出异常的风险(健壮性 - 高危)

    • 问题描述:为了解决死锁,checkAndOffShelfByAreaChange 方法中使用了 TransactionSynchronizationManager.registerSynchronization 将下架逻辑放入事务提交后执行。
    • 影响分析:registerSynchronization 方法强依赖于当前存在活跃的 Spring 事务。如果该方法在非事务上下文中被调用(例如上述提到的 AOP 失效场景,或者外层没有开启事务),该代码会直接抛出 TransactionSynchronizationException: Transaction synchronization is not active 运行时异常,导致核心业务流程阻断。
    • 优化建议: 在注册同步器之前,必须检查当前是否存在活跃的事务;如果没有,则直接执行异步逻辑。或者推荐使用 Spring 4.2+ 提供的 @TransactionalEventListener,代码更优雅且安全。 java // 修复示例:增加事务活跃状态判断 if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { taskExecutor.execute(() -> executeOffShelfLogic(...)); } }); } else { // 如果没有事务,直接提交给线程池执行 taskExecutor.execute(() -> executeOffShelfLogic(...)); }

    3. 魔法字符串硬编码降低代码可维护性(最佳实践 - 中等)

    • 问题描述:在 checkAndOffShelfByAreaChange 方法中,判断全国区域时使用了硬编码的魔法字符串 "-1".equals(a.getCityCode())。
    • 影响分析:硬编码使得代码的业务含义不透明,如果未来“全国”的标识发生变更,或者在其他地方也需要判断全国区域,极易发生遗漏,增加维护成本。
    • 优化建议: 将 "-1" 提取为常量或枚举。例如在 UpgradeGoodsArea 或相关常量类中定义 public static final String NATIONAL_CITY_CODE = "-1";。

    二、评分明细

    • 功能实现的正确性与健壮性(20/40分)

      • 扣分理由:死锁的解决思路(将异步任务推迟到事务提交后)是正确的,但具体实现存在严重的 Spring AOP 代理失效问题和事务上下文依赖问题。内部方法调用导致 @Transactional 形同虚设,且未判断事务是否活跃就注册同步器,极易在生产环境引发 TransactionSynchronizationException 异常。未发现 MyBatis 子查询和 Dubbo 接口参数违规变更。
    • 安全性与潜在风险(30/30分)

      • 得分理由:代码中使用了 MyBatis 的 Example 进行条件组装,有效防止了 SQL 注入风险。未见明显的越权、XSS 或敏感信息泄露等安全漏洞。
    • 最佳实践与可维护性(14/20分)

      • 扣分理由:存在魔法字符串(如 "-1")硬编码问题。此外,将 excludeId 传入底层校验逻辑虽然复用了代码,但 null 与非 null 混用在同一个方法中处理新增和更新逻辑,使得方法职责不够单一。
    • 性能与资源利用(4/5分)

      • 扣分理由:使用 taskExecutor 异步处理级联下架逻辑,有效提升了主线程性能。但在高并发场景下,频繁在 afterCommit 中向线程池提交任务,需确保 taskExecutor 的队列和拒绝策略配置合理,否则存在内存溢出或任务丢失风险。
    • 提交信息质量(5/5分)

      • 得分理由:Commit 信息("修复bug,新增、编辑sku一码一名校验逻辑改动... 修改产品适用区域后,下架商品逻辑因死锁导致失败...")非常清晰,不仅说明了做了什么改动,还解释了改动的背景原因(解决死锁),具有很强的可追溯性。

    总分:73分

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