@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;
}
}