# 缓存

back2专题

使用过jetcache的优雅高效

# Caffeine

返回顶部

Caffeine是一种高性能的缓存库,是基于Java 8的最佳(最优)缓存框架

Cache(缓存),基于Google Guava,Caffeine提供一个内存缓存,大大改善了设计Guava's cache 和 ConcurrentLinkedHashMap 的体验。

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .maximumSize(10_000)
    .expireAfterWrite(5, TimeUnit.MINUTES)
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(key -> createExpensiveGraph(key));
1
2
3
4
5
  • 自动加载条目到缓存中,可选异步方式
  • 可以基于大小剔除
  • 可以设置过期时间,时间可以从上次访问或上次写入开始计算
  • 异步刷新
  • keys自动包装在弱引用中
  • values自动包装在弱引用或软引用中
  • 条目剔除通知
  • 缓存访问统计

# Caffeine提供以下四种类型的加载策略

Cache<Key, Graph> cache = Caffeine.newBuilder()
     .expireAfterWrite(10, TimeUnit.MINUTES)
     .maximumSize(10_000)
     .build();

 // Lookup an entry, or null if not found
 Graph graph = cache.getIfPresent(key);
 // Lookup and compute an entry if absent, or null if not computable
 graph = cache.get(key, k -> createExpensiveGraph(key));
 // Insert or update an entry
 cache.put(key, graph);
 // Remove an entry
 cache.invalidate(key);
1
2
3
4
5
6
7
8
9
10
11
12
13
LoadingCache<Key, Graph> cache = Caffeine.newBuilder()
    .maximumSize(10_000)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .build(key -> createExpensiveGraph(key));

// Lookup and compute an entry if absent, or null if not computable
Graph graph = cache.get(key);
// Lookup and compute entries that are absent
Map<Key, Graph> graphs = cache.getAll(keys);
1
2
3
4
5
6
7
8
9
//AsyncCache是另一种Cache,它基于Executor计算条目,并返回一个CompletableFuture。
AsyncCache<Key, Graph> cache = Caffeine.newBuilder()
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .maximumSize(10_000)
    .buildAsync();

// Lookup and asynchronously compute an entry if absent
CompletableFuture<Graph> graph = cache.get(key, k -> createExpensiveGraph(key));
1
2
3
4
5
6
7
8
// AsyncLoadingCache 是关联了 AsyncCacheLoader 的 AsyncCache
AsyncLoadingCache<Key, Graph> cache = Caffeine.newBuilder()
     .maximumSize(10_000)
     .expireAfterWrite(10, TimeUnit.MINUTES)
     // Either: Build with a synchronous computation that is wrapped as asynchronous
     .buildAsync(key -> createExpensiveGraph(key));
     // Or: Build with a asynchronous computation that returns a future
     .buildAsync((key, executor) -> createExpensiveGraphAsync(key, executor));

 // Lookup and asynchronously compute an entry if absent
 CompletableFuture<Graph> graph = cache.get(key);
 // Lookup and asynchronously compute entries that are absent
 CompletableFuture<Map<Key, Graph>> graphs = cache.getAll(keys);
1
2
3
4
5
6
7
8
9
10
11
12
13

# Caffeine提供三种剔除方式:基于大小、基于时间、基于引用