文章目录
介绍
Caffeine是基于JDK1.8版本的高性能本地缓存库,它是Guava的增强版,与ConcurrentLinkedHashMap相似,支持并发,并且可以在O(1)的时间复杂度内查找、写入元素。
性能比对




使用方式
一、Population(缓存类型)
1.Cache
private static void manual() {
// 构建caffeine的缓存对象,并指定在写入后的10分钟内有效,且最大允许写入的条目数为10000
Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10_000)
.build();
String key = "hello";
// 查找某个缓存元素,若找不到则返回null
String str = cache.getIfPresent(key);
System.out.println("cache.getIfPresent(key) ---> " + str);
// 查找某个缓存元素,若找不到则调用函数生成,如无法生成则返回null
str = cache.get(key, k -> create(key));
System.out.println("cache.get(key, k -> create(key)) ---> " + str);
// 添加或者更新一个缓存元素
cache.put(key, str);
System.out.println("cache.put(key, str) ---> " + cache.getIfPresent(key));
// 移除一个缓存元素
cache.invalidate(key);
System.out.println("cache.invalidate(key) ---> " + cache.getIfPresent(key));
}
private static String create(Object key) {
return key + " world";
}
输出结果:
cache.getIfPresent(key) ---> null
cache.get(key, k -> create(key)) ---> hello world
cache.put(key, str) ---> hello world
cache.invalidate(key) ---> null
2.Loading
LoadingCache是附加在CacheLoader之上构建的缓存对象。
可以使用getAll方法执行批量查找,默认情况下,getAll()方法会单独调用CacheLoader.load()方法来加载每个不在缓存中的Key,必要情况下可以重写CacheLoader.loadAll()方法来弥补其缺陷。
public static void loading() {
LoadingCache<String, String> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(key -> create(key)); // 当调用get或者getAll时,若找不到缓存元素,则会统一调用create(key)生成
String key = "hello";
String str = cache.get(key);
System.out.println("cache.get(key) ---> " + str);
List<String> keys = Lists.newArrayList("a", "b", "c", "d", "e");
// 批量查找缓存元素,如果缓存不存在则生成缓存元素
Map<String, String> maps = cache.getAll(keys);
System.out.println("cache.getAll(keys) ---> " + maps);
}
private static String create(Object key) {
return key + " world";
}
输出结果
cache.get(key) ---> hello world
cache.getAll(keys) ---> {a=a world, b=b world, c=c world, d=d world, e=e world}
3.Asynchronous (Manual)
AsyncCache就是Cache的异步实现方式,提供了通过Executor生成缓存元素并返回CompletableFuture的能力。
synchronous()提供了在缓存计算完成前的阻塞能力,AsyncCache默认使用ForkJoinPool.commonPool()线程池,你也可以通过重写Caffeine.executor(executor)来实现自己的线程池。
private static void asynchronous() {
AsyncCache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10_000)
.buildAsync();


5196

被折叠的 条评论
为什么被折叠?



