spring boot 中緩存使用 @Cacheable redis緩存不生效的

@Cacheable 註解在對象內部調用不會生效

代碼示例:
ProductServiceImpl.java

  public List<ProductInfoVO> getProductList(CommonRequest<ProductInfoDTO> reqest) {
   // @Cacheable失效,不會走緩存的
    return  this.findProductInfoList(reqest);
  }
  
  @Cacheable(cacheNames = "productInfos",cacheManager="jfinetchRedisCacheManager", key = "'jbs:product:list:'.concat(#reqest.getChannelCode())")
  public List<ProductInfoVO> findProductInfoList(CommonRequest<ProductInfoDTO> reqest){
      List<ProductInfoVO> redisList = productService.findList(reqest);
      redisList = redisList.stream().filter(it -> ProductStatusEnum.OPEN.getCode().equals(it.getStatus())).collect(Collectors.toList());

      return redisList;
  }
  

此時getProductList 調用findProductInfoList緩存註解@Cacheable 是不會生效的

原因:
Spring 緩存註解是基於Spring AOP切面,必須走代理才能生效,同類調用或者子類調用父類帶有緩存註解的方法時屬於內部調用,沒有走代理,所以註解不生效。
解決方法: 將方法抽離到一個獨立類中,代碼示例如下:
ProductServiceImpl.java

 @Autowired
 private ProductBiz productBiz;
    
 public List<ProductInfoVO> getProductList(CommonRequest<ProductInfoDTO> reqest) {
	//第二次調用走緩存
   return  productBiz.findProductInfoList(reqest);
 }

ProductBiz .java

@Service
@Slf4j
public class ProductBiz {

    @Autowired
    private IProductService productService;

    @Cacheable(cacheNames = "productInfos",cacheManager="jfinetchRedisCacheManager", key = "'jbs:product:list:'.concat(#reqest.getChannelCode())")
    public List<ProductInfoVO> findProductInfoList(CommonRequest<ProductInfoDTO> reqest){
        List<ProductInfoVO> redisList = productService.findList(reqest);
        redisList = redisList.stream().filter(it -> ProductStatusEnum.OPEN.getCode().equals(it.getStatus())).collect(Collectors.toList());

        return redisList;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章