如果想使用 緩存朦佩,但是又覺得 redis 這種nosql 網(wǎng)絡開銷大并思。
又想有緩存大小、過期時間這種特性吕粗。guava的cache是一個不錯的選擇纺荧。
下面通過兩個demon 來展示下guava的緩存如何使用。
1. Cache
//創(chuàng)建 cache 颅筋,過期時間 2 s
Cache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.SECONDS)
.build();
//向緩存中添加 數(shù)據(jù) 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后就沒有數(shù)據(jù)了议泵。
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