分享

使用@Cacheable 踩过的坑

 bylele 2021-07-08
public class XXX{
    
@Resource
private XXX self;//@Cacheable通过内部调用将不会使用缓存,从Spring4.3开始可以通过注入self,再通过self内部调用即可解决
public final static String MY_KEY="my_key:";

@Cacheable(value=MY_KEY, key = "#root.target.getFormatKey(#p0,#p1)", unless="#result == null")//自定义key名称,查询结果为空则不缓存
public xXXEntity select(Date date,String str) {
return xXXdao.select(date, str);
}

public String getFormatKey(Date date,String str){//生成key
return DateUtils.getFormat(date)+sourceKey;//格式化时间拼接key
}
public Integer selectValue(Date date,String str) {
  xXXEntity entity = self.select(date, str);//解决内部调用不触发缓存的问题
    if(entity!=null){
return entity.getValue();
}
return 0;
}


}

1.解析:
value=MY_KEY -->redisz缓存中的key
生成redis中hash的key = "#root.target.getFormatKey(#p0,#p1)"  -->当前调用对象中的方法,传入第一个和第二个参数
unless="#result == null" -->查询结果为空则不缓存(不加上会缓存一个空对象,拿值就悲剧了)




2.内部调用不触发缓存
方法一:https://www.cnblogs.com/cyhbyw/p/8615816.html 侵删

方法二(推荐):https:///questions/16899604/spring-cache-cacheable-not-working-while-calling-from-another-method-of-the-s/48867068#48867068
 代码中有提现,思路:注入自己,然后通过注入的实例调用自己的方法来触发缓存机制.

@Resource
private XXX self;//@Cacheable通过内部调用将不会使用缓存,从Spring4.3开始可以通过注入self,再通过self内部调用即可解决

@Cacheable(value=MY_KEY, key = "#root.target.getFormatKey(#p0,#p1)", unless="#result == null")//自定义key名称,查询结果为空则不缓存
public xXXEntity select(Date date,String str) {
return xXXdao.select(date, str);
}
public Integer selectValue(Date date,String str) {
  xXXEntity entity = self.select(date, str);//解决内部调用不触发缓存的问题
    if(entity!=null){
return entity.getValue();
}
return 0;
}

  
}
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多