guava 缓存使用

作者: 良人与我 | 来源:发表于2018-12-22 22:33 被阅读2次

如果想使用 缓存,但是又觉得 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

相关文章

  • 高并发系统技术梳理

    缓存 缓存使用常见问题归纳Guava Cache系列之一Guava Cache系列之二Guava Cache系列之...

  • Guava Cache

    原文 使用Guava cache构建本地缓存 - sameLuo的个人空间 - OSCHINA Guava Cac...

  • Guava Cache用法介绍

    Guava Cache的使用场景 参考1 Guava Cache用法介绍2 分布式系统缓存系列之guava cache

  • Java内存缓存-通过Google Guava创建缓存

    谷歌Guava缓存 Guava介绍 Guava是Google guava中的一个内存缓存模块,用于将数据缓存到JV...

  • guava 缓存使用

    如果想使用 缓存,但是又觉得 redis 这种nosql 网络开销大。又想有缓存大小、过期时间这种特性。guava...

  • java之guava cache应用

    google的guava cache是一个轻量级进程内缓存框架。 如何使用guava cache a. 引入方便,...

  • Guava使用

    Guava中针对集合的 filter和过滤功能 缓存 测试 配置 缓存使用 测试 转换器:利用 Collectio...

  • Guava缓存

    Guava缓存是谷歌的一种本地缓存,缓存是通过使用本机的内存来存储的,实现原理类似于ConcurrentHashM...

  • 缓存

    堆缓存堆外缓存磁盘缓存分布式缓存 Guava CacheEHcacheMapDBmemcachedTerracot...

  • Guava Cache系列之二:如何回收缓存

    上一篇文章:Guava Cache系列之一:如何加载缓存 回收缓存方案 Guava Cache提供了三种基本的缓存...

网友评论

    本文标题:guava 缓存使用

    本文链接:https://www.haomeiwen.com/subject/rsqskqtx.html