guava cache学习

来源:互联网 发布:windows无法正确加载 编辑:程序博客网 时间:2024/06/18 18:01

</pre>guava  cache 是本地缓存的一种实现,他与平常使用map 来实现本地缓存的不同之处就是 guava cache 可以让我们自己定义自己的缓存。</h4><h4><span style="font-weight: normal;"><span style="font-family:Microsoft YaHei;font-size:12px;">一  总体来说guava cache有两种实现方式:</span></span></h4><div><span style="font-family:Microsoft YaHei;font-size:12px;">第一种就是在定义cache 的时候就定义了数据的获取方式</span></div><div><span style="font-family:Microsoft YaHei;font-size:12px;">  </span></div><div><span style="font-family:Microsoft YaHei;font-size:12px;">        LoadingCache<String, String> cahceBuilder = CacheBuilder                .newBuilder()                .build(new CacheLoader<String, String>() {                    @Override                    public String load(String key) throws Exception {                        String strProValue = "hello " + key + "!";                        return strProValue;                    }                });</span></div><div><span style="font-family:Microsoft YaHei;font-size:12px;"></span></div><div><span style="font-family:Microsoft YaHei;font-size:12px;">第二种是在获取数据的时候在定义,这种会比较灵活</span></div><div><span style="font-family:Microsoft YaHei;font-size:12px;"></span></div><div><pre name="code" class="java"><span style="font-family:Microsoft YaHei;font-size:12px;">Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();          String resultVal = cache.get("jerry", new Callable<String>() {              public String call() {                  String strProValue="hello "+"jerry"+"!";                                return strProValue;            }          }); </span>


二  就是guava  cache 可以让我们自己定义缓存的一些特性  包括

       2.1失效时间的设置: 
           主要有按大小失效        方法是CacheBuilder.maximumSize(long)  ;
         基于时间的失效      expireAfterAccess(long, TimeUnit) 最后一次访问(读或者写)超过一定时间后失效。expireAfterWrite(long, TimeUnit) 最后一次                                          写(或者对象生成)超过一定时间后失效;
         基于引用的失效      CacheBuilder.weakKeys() 和CacheBuilder.weakValues()    key 的弱引用和value 的弱引用
         手动失效数据
    
  2.2  其他的使用
          可以转成map 来使用,方法是asmap() 

0 0
原创粉丝点击