优化后的代码:

List<FreightPriceDto> freightPriceDtoList = new LinkedList<>();
Map<Long, Integer> productMap = new LinkedHashMap<>();
List<Long> notTempIdProduct = new LinkedList<>();

//查询商品对应的模板id
for (Long productId : productIds) {
    ProductVo productInfo = cache.get('PRODUCT_DETAIL_CACHE' + productId);
    if (productInfo != null && productInfo.getProductInfo() != null && productInfo.getProductInfo().getTempId() != null) {
        Integer tempId = productInfo.getProductInfo().getTempId();
        productMap.put(productId, tempId);
    } else {
        notTempIdProduct.add(productId);
    }
}

//缓存没有的远程抵用查询商品详情信息
if (CollectionUtil.isNotEmpty(notTempIdProduct)) {
    Map<Long, ProductVo> productDetail = iProductApi.muchProductDetail(notTempIdProduct, 1);
    if (productDetail != null) {
        for (Long productId : productDetail.keySet()) {
            ProductVo productVo = productDetail.get(productId);
            if (productVo != null && productVo.getProductInfo() != null && productVo.getProductInfo().getTempId() != null) {
                productMap.put(productId, productVo.getProductInfo().getTempId());
            }
        }
    }
}

for (Map.Entry<Long, Integer> entry : productMap.entrySet()) {
    Long productId = entry.getKey();
    Integer tempId = entry.getValue();
    FreightPriceDto freightPriceDto = new FreightPriceDto();
    freightPriceDto.setProductId(productId);
    freightPriceDto.setTemplatesRegions(templateRegionListLocalCache.get('TEMPLATE_REGION' + tempId,
        () -> yxShippingTemplatesRegionMapper.selectList(new LambdaQueryWrapper<YxShippingTemplatesRegion>()
            .eq(YxShippingTemplatesRegion::getTempId, tempId))));
    freightPriceDto.setRegionInfo(productUnDelivery(tempId));
    freightPriceDtoList.add(freightPriceDto);
}

return freightPriceDtoList;

优化说明:

  1. 使用 Map.Entry 遍历 productMap,避免了通过 keySet 获取 value 的过程,提高了效率。
  2. 使用 lambda 表达式设置本地缓存,避免了手动设置缓存的繁琐过程。
  3. 将获取模板不可配送区域的代码提取出来,避免了多次调用该方法的重复代码。

通过以上优化,代码更加简洁高效,提高了可读性和性能。

Java 代码优化:提高商品运费计算效率

原文地址: https://www.cveoy.top/t/topic/ovp9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录