使用@Cacheable 踩过的坑

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://stackoverflow.com/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;
}

  
}
 

猜你喜欢

转载自www.cnblogs.com/zou-rong/p/10279094.html
今日推荐