转载:http://outofmemory.cn/java/guava/cache/how-to-use-guava-cache

     http://www.cnblogs.com/parryyang/p/5777019.html

     https://yq.aliyun.com/articles/46900            //源码解析

 

  作为Google的core libraries,直接提供Cache实现,足以证明Cache应用的广泛程度。 然而作为工具库中的一部分,我们自然不能期待Guava对Cache有比较完善的实现。因而Guava中的Cache只能用于一些把Cache作为一种辅助设计的项目或者在项目的前期为了实现简单而引入。

Guava Cache有两种创建方式:

  1. cacheLoader
  2. callable callback

  通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于,这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。但不同的在于cacheloader的定义比较宽泛,是针对整个cache定义的,可以认为是统一的根据key值load value的方法。而callable的方式较为灵活,允许你在get的时候指定。

cacheLoader方式实现实例:

public static void main(String[] args) throws ExecutionException, InterruptedException{
        //缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
        LoadingCache<Integer,Student> studentCache
                //CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
                = CacheBuilder.newBuilder()
                //设置并发级别为8,并发级别是指可以同时写缓存的线程数
          //refreshAfterWrite(3, TimeUnit.HOURS)// 给定时间内没有被读/写访问,则回收。                 .concurrencyLevel(8)                 //设置写缓存后8秒钟过期                 .expireAfterWrite(8, TimeUnit.SECONDS)                 //设置缓存容器的初始容量为10                 .initialCapacity(10)                 //设置缓存最大容量为100,超过100之后就会按照LRU最近虽少使用算法来移除缓存项                 .maximumSize(100)                 //设置要统计缓存的命中率                 .recordStats()                 //设置缓存的移除通知                 .removalListener(new RemovalListener<Object, Object>() {                     @Override                     public void onRemoval(RemovalNotification<Object, Object> notification) {                         System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause());                     }                 })                 //build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
          ///** 当本地缓存命没有中时,调用load方法获取结果并将结果缓存 **/                   .build(                         new CacheLoader<Integer, Student>() {                             @Override                             public Student load(Integer key) throws Exception {                                 System.out.println("load student " + key);                                 Student student = new Student();                                 student.setId(key);                                 student.setName("name " + key);                                 return student;                             }                         }                 );         for (int i=0;i<20;i++) {             //从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据             Student student = studentCache.get

相关文章: