`
decao
  • 浏览: 77749 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Google Guava缓存

阅读更多

适用性

  缓存在很多情况下非常实用。例如,计算或检索一个值的代价很高,并且对同样的输入需要不止一次获取值的时候,就应当考虑使用缓存。

  Guava CacheConcurrentMap很相似,但也不完全一样。最基本的区别是ConcurrentMap会一直保存所添加的元素,直到显式的移除;Guava Cache为了限制内存的占用,通常都是设定为自动回收元素。在某些场景下,尽管LoadingCahe不回收元素,但是它还是很有用的,因为它会自动加载缓存。

  Guava Cache适用场景:

  • 你愿意消耗一部分内存来提升速度;
  • 你已经预料某些值会被多次调用;
  • 缓存数据不会超过内存总量;

 Guava Cache是一个全内存的本地缓存实现,它提供了线程安全的实现机制。整体上来说Guava cache 是本地缓存的不二之选,简单易用,性能好。

创建方式

  CacheLoaderCallable通过这两种方法创建的cache,和通常用map来缓存的做法比,不同在于这两种方法都实现了一种逻辑——从缓存中取key X的值,如果该值已经缓存过了,则返回缓存中的值,如果没有缓存过,可以通过某个方法来获取这个值。

  但不同的在于cacheloader的定义比较宽泛, 是针对整个cache定义的,可以认为是统一的根据key值load value的方法。而callable的方式较为灵活,允许你在get的时候指定。

1、CacheLoader

//缓存接口这里是LoadingCache,LoadingCache在缓存项不存在时可以自动加载缓存
        LoadingCache<Integer,String> strCache
                //CacheBuilder的构造函数是私有的,只能通过其静态方法newBuilder()来获得CacheBuilder的实例
                = CacheBuilder.newBuilder()
                //设置并发级别为100,并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(100)
                //设置写缓存后60秒钟过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                //设置缓存容器的初始容量为1000
                .initialCapacity(1000)
                //设置缓存最大容量为10000,超过10000之后就会按照LRU最近虽少使用算法来移除缓存项
                .maximumSize(10000)
                //设置要统计缓存的命中率
                .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的实现自动加载缓存
                .build(
                        new CacheLoader<Integer, String>() {
                            @Override
                            public String load(Integer key) throws Exception {
                                System.out.println("load cache " + key);
                                String str = "";
                                return str;
                            }
                        }
                );

        for (int i=0;i<20;i++) {
            //从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
            String str = strCache.get(1);
            System.out.println(str);
            //休眠1秒
            TimeUnit.SECONDS.sleep(1);
        }

        System.out.println("cache stats:");
        //最后打印缓存的命中率等 情况
        System.out.println(strCache.stats().toString());

 2、Callable

public void testcallableCache()throws Exception{
        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;
            }  
        });  
        System.out.println("jerry value : " + resultVal);
        
        resultVal = cache.get("peida", new Callable<String>() {  
            public String call() {  
                String strProValue="hello "+"peida"+"!";                
                return strProValue;
            }  
        });  
        System.out.println("peida value : " + resultVal);  
    }

 

 

    guava的内存缓存非常强大,可以设置各种选项,而且很轻量,使用方便。另外还提供了下面一些方法,来方便各种需要:

1、ImmutableMap<K, V> getAllPresent(Iterable<?> keys) 一次获得多个键的缓存值

2、putAll方法向缓存中添加一个或者多个缓存项

3、invalidateAll方法从缓存中移除缓存项

4、ConcurrentMap<K, V>快照

5、refresh(Key) 刷新缓存,即重新取缓存数据,更新缓存

分享到:
评论

相关推荐

    使用google guava 实现定时缓存功能

    使用google guava 实现定时缓存功能

    Guava-Cache-Demo:演示如何使用 Guava 缓存

    Guava-Cache-Demo 演示如何使用 Guava 缓存。 此示例应用程序使用 Google Books API 获取给定 ISBN 的图书的详细信息。

    Google Guava 多版本集合

    Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法...

    com.google.common guava 18.0 JAR包

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    Guava官方教程-中文

    Google Guava是一个比较有趣的框架,它提供了很多有趣的的功能, google Guava 给开发者提供了如下常用功能: 集合(collections) 缓存(caching) 原生的类型支持(primitives support) 并发类库(concurrency ...

    Google开源Guava包让使用Java语言变得更舒适

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    Guava 16.0 API (CHM格式)

    Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你...

    Java8的高性能缓存库caffeine.zip

    改进取决于您设计Guava缓存和ConcurrentLinkedHashMap的体验。LoadingCache, Graph&gt; graphs = Caffeine.newBuilder()  .maximumSize(10_000)  .expireAfterWrite(5, TimeUnit.MINUTES)  ....

    Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库.zip

    Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法...

    Guava-23.6最新版源代码

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    Guava-CacheDemo.rar

    Google Guava-Cache 详细注释。。。。。。。。。。。。。。。。。。。。。。(凑足50字)

    google-guava

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    guava jar包

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    guava-22.0.jar

    Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法...

    guava-27.1.chm

    guava-27.1版本的chm格式的api文档,Guava包含了若干被Google的Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、...

    guava14.0.1jar包及API文档

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    guava-14.0.1.jar

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

    Learning-Guava:突出显示 Google Guava 功能的代码片段

    学习番石榴介绍是一个项目,其中包含 Google 在其基于 Java 的项目中依赖的几个核心库,例如集合、缓存、原语支持、并发库、通用注释、字符串处理、I/O 等。 Guava 被许多应用程序使用 /构架。 只是为了突出 Guava ...

    GuavaGoogle的Java核心库

    Guava项目包含了很多Java项目开发中依赖的Google核心库:集合、缓存、基础类型支持、并发库、通用注解、字符串处理、I/O等等。

    guava-21.0.jar

    Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] ...

Global site tag (gtag.js) - Google Analytics