zoukankan      html  css  js  c++  java
  • 使用@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;
    }

      
    }
     
  • 相关阅读:
    JasperReports项目中的应用
    请问两个div之间的上下距离怎么设置
    Spring MVC Flash Attribute 的讲解与使用示例
    8.ireport 取消自动分页,detail不分页
    python网络爬虫学习笔记
    ShareSDK for Android 2.3.8它已发表
    OllyDbg 使用注意事项 (十)
    ListView的cacheColorHint与listSelector物业和fragment里面onActivityResult问题没有响应
    Hdu 3341 Lost's revenge (ac+自己主动机dp+hash)
    PhoneGap 开发与应用 上传 App Store 在
  • 原文地址:https://www.cnblogs.com/zou-rong/p/10279094.html
Copyright © 2011-2022 走看看