guava 缓存使用

如果想使用 缓存,但是又觉得 redis 这种nosql 网络开销大。
又想有缓存大小、过期时间这种特性。guava的cache是一个不错的选择。
下面通过两个demon 来展示下guava的缓存如何使用。

1. Cache

//创建 cache ,过期时间 2 s
Cache<String, String> cache = CacheBuilder.newBuilder()
        .expireAfterWrite(2, TimeUnit.SECONDS)
        .build();
//向缓存中添加 数据 K V 形式
cache.put("hello","where are you");
// 获取 key = hello 的 值
System.out.println(cache.getIfPresent("hello"));
// 延迟3 秒
Thread.sleep(1000 * 3);
// return null if not present
System.out.println(cache.getIfPresent("hello"));

输出结果 如下,过期时间是2s,在3s后就没有数据了。

where are you
null

2. LoadingCache

LoadingCache 和 cache 的用法差不多,但是可以自定义load方法,当找不到key 时候可以定义如何加载

LoadingCache<String, String> graphs = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(10, TimeUnit.SECONDS)
                .build(
                        new CacheLoader<String, String>() {
                            @Override
                            public String load(String key) {
                                System.out.println("load key :" + key);
                                return key + " :value";
                            }
                        }
                );
System.out.println(graphs.getUnchecked("hello"));
System.out.println(graphs.getUnchecked("hello"));

结果如下,
第一次get时候通过load 方法加载,第二次get时候走的缓存。

load key :hello
hello :value
hello :value

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 缓存在应用中是必不可少的,经常用的如redis、memcache以及内存缓存等。Guava是Google出的一个工...
    timothyue1阅读 1,641评论 1 1
  • Guava Cache以下的特性: automatic loading of entries into the c...
    小锄禾阅读 8,657评论 2 11
  • com.google.common.cache 1、背景 缓存,在我们日常开发中是必不可少的一种解决性能问题的方法...
    拾壹北阅读 22,481评论 0 25
  • 看到妹妹在空间分享一个说说,表达的是她心中认为的自己的好朋友的名字,并且表示自己从不后悔遇见那些同学。...
    仓楊阅读 506评论 0 0