在本文中,我們來看看 Caffeine — 一個高性能的 Java 緩存庫。
緩存和 Map 之間的一個根本區別在於緩存可以回收存儲的 item。
回收策略為在指定時間刪除哪些對象。此策略直接影響緩存的命中率 — 緩存庫的一個重要特征。
Caffeine 因使用 Window TinyLfu 回收策略,提供了一個近乎最佳的命中率。
填充策略(Population)
Caffeine 為我們提供了三種填充策略:手動、同步和異步
手動加載(Manual)
Cache<String, Object> manualCache = Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10_000) .build(); String key = "name1"; // 根據key查詢一個緩存,如果沒有返回NULL graph = manualCache.getIfPresent(key); // 根據Key查詢一個緩存,如果沒有調用createExpensiveGraph方法,並將返回值保存到緩存。 // 如果該方法返回Null則manualCache.get返回null,如果該方法拋出異常則manualCache.get拋出異常 graph = manualCache.get(key, k -> createExpensiveGraph(k)); // 將一個值放入緩存,如果以前有值就覆蓋以前的值 manualCache.put(key, graph); // 刪除一個緩存 manualCache.invalidate(key); ConcurrentMap<String, Object> map = manualCache.asMap(); cache.invalidate(key);
Cache接口允許顯式的去控制緩存的檢索,更新和刪除。
我們可以通過cache.getIfPresent(key) 方法來獲取一個key的值,通過cache.put(key, value)方法顯示的將數控放入緩存,但是這樣子會覆蓋緩原來key的數據。更加建議使用cache.get(key,k - > value) 的方式,get 方法將一個參數為 key 的 Function (createExpensiveGraph) 作為參數傳入。如果緩存中不存在該鍵,則調用這個 Function 函數,並將返回值作為該緩存的值插入緩存中。get 方法是以阻塞方式執行調用,即使多個線程同時請求該值也只會調用一次Function方法。這樣可以避免與其他線程的寫入競爭,這也是為什么使用 get 優於 getIfPresent 的原因。
注意:如果調用該方法返回NULL(如上面的 createExpensiveGraph 方法),則cache.get返回null,如果調用該方法拋出異常,則get方法也會拋出異常。
可以使用Cache.asMap() 方法獲取ConcurrentMap進而對緩存進行一些更改。
同步加載(Loading)
LoadingCache<String, Object> loadingCache = Caffeine.newBuilder()
.maximumSize(10_000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key)); String key = "name1"; // 采用同步方式去獲取一個緩存和上面的手動方式是一個原理。在build Cache的時候會提供一個createExpensiveGraph函數。 // 查詢並在缺失的情況下使用同步的方式來構建一個緩存 Object graph = loadingCache.get(key); // 獲取組key的值返回一個Map List<String> keys = new ArrayList<>(); keys.add(key); Map<String, Object> graphs = loadingCache.getAll(keys);
LoadingCache是使用CacheLoader來構建的緩存的值。
批量查找可以使用getAll方法。默認情況下,getAll將會對緩存中沒有值的key分別調用CacheLoader.load方法來構建緩存的值。我們可以重寫CacheLoader.loadAll方法來提高getAll的效率。
注意:您可以編寫一個CacheLoader.loadAll來實現為特別請求的key加載值。例如,如果計算某個組中的任何鍵的值將為該組中的所有鍵提供值,則loadAll可能會同時加載該組的其余部分。
異步加載(Asynchronously Loading)
AsyncLoadingCache<String, Object> asyncLoadingCache = 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)); String key = "name1"; // 查詢並在缺失的情況下使用異步的方式來構建緩存 CompletableFuture<Object> graph = asyncLoadingCache.get(key); // 查詢一組緩存並在缺失的情況下使用異步的方式來構建緩存 List<String> keys = new ArrayList<>(); keys.add(key); CompletableFuture<Map<String, Object>> graphs = asyncLoadingCache.getAll(keys); // 異步轉同步 loadingCache = asyncLoadingCache.synchronous();
AsyncLoadingCache是繼承自LoadingCache類的,異步加載使用Executor去調用方法並返回一個CompletableFuture。異步加載緩存使用了響應式編程模型。
如果要以同步方式調用時,應提供CacheLoader。要以異步表示時,應該提供一個AsyncCacheLoader,並返回一個CompletableFuture。
synchronous()這個方法返回了一個LoadingCacheView視圖,LoadingCacheView也繼承自LoadingCache。調用該方法后就相當於你將一個異步加載的緩存AsyncLoadingCache轉換成了一個同步加載的緩存LoadingCache。
默認使用ForkJoinPool.commonPool()來執行異步線程,但是我們可以通過Caffeine.executor(Executor) 方法來替換線程池。
驅逐策略(eviction)
Caffeine提供三類驅逐策略:基於大小(size-based),基於時間(time-based)和基於引用(reference-based)。
基於大小(size-based)
基於大小驅逐,有兩種方式:一種是基於緩存大小,一種是基於權重。
// Evict based on the number of entries in the cache // 根據緩存的計數進行驅逐 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .maximumSize(10_000) .build(key -> createExpensiveGraph(key)); // Evict based on the number of vertices in the cache // 根據緩存的權重來進行驅逐(權重只是用於確定緩存大小,不會用於決定該緩存是否被驅逐) LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .maximumWeight(10_000) .weigher((Key key, Graph graph) -> graph.vertices().size()) .build(key -> createExpensiveGraph(key));
我們可以使用Caffeine.maximumSize(long)方法來指定緩存的最大容量。當緩存超出這個容量的時候,會使用Window TinyLfu策略來刪除緩存。
我們也可以使用權重的策略來進行驅逐,可以使用Caffeine.weigher(Weigher) 函數來指定權重,使用Caffeine.maximumWeight(long) 函數來指定緩存最大權重值。
maximumWeight與maximumSize不可以同時使用。
基於時間(Time-based)
// Evict based on a fixed expiration policy // 基於固定的到期策略進行退出 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key)); LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key)); // Evict based on a varying expiration policy // 基於不同的到期策略進行退出 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .expireAfter(new Expiry<Key, Graph>() { @Override public long expireAfterCreate(Key key, Graph graph, long currentTime) { // Use wall clock time, rather than nanotime, if from an external resource long seconds = graph.creationDate().plusHours(5) .minus(System.currentTimeMillis(), MILLIS) .toEpochSecond(); return TimeUnit.SECONDS.toNanos(seconds); } @Override public long expireAfterUpdate(Key key, Graph graph, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(Key key, Graph graph, long currentTime, long currentDuration) { return currentDuration; } }) .build(key -> createExpensiveGraph(key));
Caffeine提供了三種定時驅逐策略:
- expireAfterAccess(long, TimeUnit):在最后一次訪問或者寫入后開始計時,在指定的時間后過期。假如一直有請求訪問該key,那么這個緩存將一直不會過期。
- expireAfterWrite(long, TimeUnit): 在最后一次寫入緩存后開始計時,在指定的時間后過期。
- expireAfter(Expiry): 自定義策略,過期時間由Expiry實現獨自計算。
緩存的刪除策略使用的是惰性刪除和定時刪除。這兩個刪除策略的時間復雜度都是O(1)。
測試定時驅逐不需要等到時間結束。我們可以使用Ticker接口和Caffeine.ticker(Ticker)方法在緩存生成器中指定時間源,而不必等待系統時鍾。如:
FakeTicker ticker = new FakeTicker(); // Guava's testlib Cache<Key, Graph> cache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .executor(Runnable::run) .ticker(ticker::read) .maximumSize(10) .build(); cache.put(key, graph); ticker.advance(30, TimeUnit.MINUTES) assertThat(cache.getIfPresent(key), is(nullValue());
基於引用(reference-based)
強引用,軟引用,弱引用概念說明請點擊連接,這里說一下各各引用的區別:
Java4種引用的級別由高到低依次為:強引用 > 軟引用 > 弱引用 > 虛引用
| 引用類型 | 被垃圾回收時間 | 用途 | 生存時間 |
|---|---|---|---|
| 強引用 | 從來不會 | 對象的一般狀態 | JVM停止運行時終止 |
| 軟引用 | 在內存不足時 | 對象緩存 | 內存不足時終止 |
| 弱引用 | 在垃圾回收時 | 對象緩存 | gc運行后終止 |
| 虛引用 | Unknown | Unknown | Unknown |
// Evict when neither the key nor value are strongly reachable // 當key和value都沒有引用時驅逐緩存 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .weakKeys() .weakValues() .build(key -> createExpensiveGraph(key)); // Evict when the garbage collector needs to free memory // 當垃圾收集器需要釋放內存時驅逐 LoadingCache<Key, Graph> graphs = Caffeine.newBuilder() .softValues() .build(key -> createExpensiveGraph(key));
我們可以將緩存的驅逐配置成基於垃圾回收器。為此,我們可以將key 和 value 配置為弱引用或只將值配置成軟引用。
注意:AsyncLoadingCache不支持弱引用和軟引用。
Caffeine.weakKeys() 使用弱引用存儲key。如果沒有其他地方對該key有強引用,那么該緩存就會被垃圾回收器回收。由於垃圾回收器只依賴於身份(identity)相等,因此這會導致整個緩存使用身份 (==) 相等來比較 key,而不是使用 equals()。
Caffeine.weakValues() 使用弱引用存儲value。如果沒有其他地方對該value有強引用,那么該緩存就會被垃圾回收器回收。由於垃圾回收器只依賴於身份(identity)相等,因此這會導致整個緩存使用身份 (==) 相等來比較 key,而不是使用 equals()。
Caffeine.softValues() 使用軟引用存儲value。當內存滿了過后,軟引用的對象以將使用最近最少使用(least-recently-used ) 的方式進行垃圾回收。由於使用軟引用是需要等到內存滿了才進行回收,所以我們通常建議給緩存配置一個使用內存的最大值。 softValues() 將使用身份相等(identity) (==) 而不是equals() 來比較值。
注意:Caffeine.weakValues()和Caffeine.softValues()不可以一起使用。
移除監聽器(Removal)
概念:
- 驅逐(eviction):由於滿足了某種驅逐策略,后台自動進行的刪除操作
- 無效(invalidation):表示由調用方手動刪除緩存
- 移除(removal):監聽驅逐或無效操作的監聽器
手動刪除緩存:
在任何時候,您都可能明確地使緩存無效,而不用等待緩存被驅逐。
// individual key cache.invalidate(key) // bulk keys cache.invalidateAll(keys) // all keys cache.invalidateAll()
Removal 監聽器:
Cache<Key, Graph> graphs = Caffeine.newBuilder()
.removalListener((Key key, Graph graph, RemovalCause cause) ->
System.out.printf("Key %s was removed (%s)%n", key, cause)) .build();
您可以通過Caffeine.removalListener(RemovalListener) 為緩存指定一個刪除偵聽器,以便在刪除數據時執行某些操作。 RemovalListener可以獲取到key、value和RemovalCause(刪除的原因)。
刪除偵聽器的里面的操作是使用Executor來異步執行的。默認執行程序是ForkJoinPool.commonPool(),可以通過Caffeine.executor(Executor)覆蓋。當操作必須與刪除同步執行時,請改為使用CacheWrite,CacheWrite將在下面說明。
注意:由RemovalListener拋出的任何異常都會被記錄(使用Logger)並不會拋出。
刷新(Refresh)
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.maximumSize(10_000) // 指定在創建緩存或者最近一次更新緩存后經過固定的時間間隔,刷新緩存 .refreshAfterWrite(1, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key));
刷新和驅逐是不一樣的。刷新的是通過LoadingCache.refresh(key)方法來指定,並通過調用CacheLoader.reload方法來執行,刷新key會異步地為這個key加載新的value,並返回舊的值(如果有的話)。驅逐會阻塞查詢操作直到驅逐作完成才會進行其他操作。
與expireAfterWrite不同的是,refreshAfterWrite將在查詢數據的時候判斷該數據是不是符合查詢條件,如果符合條件該緩存就會去執行刷新操作。例如,您可以在同一個緩存中同時指定refreshAfterWrite和expireAfterWrite,只有當數據具備刷新條件的時候才會去刷新數據,不會盲目去執行刷新操作。如果數據在刷新后就一直沒有被再次查詢,那么該數據也會過期。
刷新操作是使用Executor異步執行的。默認執行程序是ForkJoinPool.commonPool(),可以通過Caffeine.executor(Executor)覆蓋。
如果刷新時引發異常,則使用log記錄日志,並不會拋出。
Writer
LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.writer(new CacheWriter<Key, Graph>() { @Override public void write(Key key, Graph graph) { // write to storage or secondary cache } @Override public void delete(Key key, Graph graph, RemovalCause cause) { // delete from storage or secondary cache } }) .build(key -> createExpensiveGraph(key));
CacheWriter允許緩存充當一個底層資源的代理,當與CacheLoader結合使用時,所有對緩存的讀寫操作都可以通過Writer進行傳遞。Writer可以把操作緩存和操作外部資源擴展成一個同步的原子性操作。並且在緩存寫入完成之前,它將會阻塞后續的更新緩存操作,但是讀取(get)將直接返回原有的值。如果寫入程序失敗,那么原有的key和value的映射將保持不變,如果出現異常將直接拋給調用者。
CacheWriter可以同步的監聽到緩存的創建、變更和刪除操作。加載(例如,LoadingCache.get)、重新加載(例如,LoadingCache.refresh)和計算(例如Map.computeIfPresent)的操作不被CacheWriter監聽到。
注意:CacheWriter不能與weakKeys或AsyncLoadingCache結合使用。
可能的用例(Possible Use-Cases)
CacheWriter是復雜工作流的擴展點,需要外部資源來觀察給定Key的變化順序。這些用法Caffeine是支持的,但不是本地內置。
寫模式(Write Modes)
CacheWriter可以用來實現一個直接寫(write-through )或回寫(write-back )緩存的操作。
write-through式緩存中,寫操作是一個同步的過程,只有寫成功了才會去更新緩存。這避免了同時去更新資源和緩存的條件競爭。
write-back式緩存中,對外部資源的操作是在緩存更新后異步執行的。這樣可以提高寫入的吞吐量,避免數據不一致的風險,比如如果寫入失敗,則在緩存中保留無效的狀態。這種方法可能有助於延遲寫操作,直到指定的時間,限制寫速率或批寫操作。
通過對write-back進行擴展,我們可以實現以下特性:
- 批處理和合並操作
- 延遲操作並到一個特定的時間執行
- 如果超過閾值大小,則在定期刷新之前執行批處理
- 如果操作尚未刷新,則從寫入后緩沖器(write-behind)加載
- 根據外部資源的特點,處理重審,速率限制和並發
可以參考一個簡單的例子,使用RxJava實現。
分層(Layering)
CacheWriter可能用來集成多個緩存進而實現多級緩存。
多級緩存的加載和寫入可以使用系統外部高速緩存。這允許緩存使用一個小並且快速的緩存去調用一個大的並且速度相對慢一點的緩存。典型的off-heap、file-based和remote 緩存。
受害者緩存(Victim Cache)是一個多級緩存的變體,其中被刪除的數據被寫入二級緩存。這個delete(K, V, RemovalCause) 方法允許檢查為什么該數據被刪除,並作出相應的操作。
同步監聽器(Synchronous Listeners)
同步監聽器會接收一個key在緩存中的進行了那些操作的通知。監聽器可以阻止緩存操作,也可以將事件排隊以異步的方式執行。這種類型的監聽器最常用於復制或構建分布式緩存。
統計(Statistics)
Cache<Key, Graph> graphs = Caffeine.newBuilder()
.maximumSize(10_000) .recordStats() .build();
使用Caffeine.recordStats(),您可以打開統計信息收集。Cache.stats() 方法返回提供統計信息的CacheStats,如:
- hitRate():返回命中與請求的比率
- hitCount(): 返回命中緩存的總數
- evictionCount():緩存逐出的數量
- averageLoadPenalty():加載新值所花費的平均時間
Cleanup
緩存的刪除策略使用的是惰性刪除和定時刪除,但是我也可以自己調用cache.cleanUp()方法手動觸發一次回收操作。cache.cleanUp()是一個同步方法。
策略(Policy)
在創建緩存的時候,緩存的策略就指定好了。但是我們可以在運行時可以獲得和修改該策略。這些策略可以通過一些選項來獲得,以此來確定緩存是否支持該功能。
Size-based
cache.policy().eviction().ifPresent(eviction -> {
eviction.setMaximum(2 * eviction.getMaximum()); });
如果緩存配置的時基於權重來驅逐,那么我們可以使用weightedSize() 來獲取當前權重。這與獲取緩存中的記錄數的Cache.estimatedSize() 方法有所不同。
緩存的最大值(maximum)或最大權重(weight)可以通過getMaximum()方法來讀取,並使用setMaximum(long)進行調整。當緩存量達到新的閥值的時候緩存才會去驅逐緩存。
如果有需用我們可以通過hottest(int) 和 coldest(int)方法來獲取最有可能命中的數據和最有可能驅逐的數據快照。
Time-based
cache.policy().expireAfterAccess().ifPresent(expiration -> ...);
cache.policy().expireAfterWrite().ifPresent(expiration -> ...);
cache.policy().expireVariably().ifPresent(expiration -> ...);
cache.policy().refreshAfterWrite().ifPresent(expiration -> ...);
ageOf(key,TimeUnit) 提供了從expireAfterAccess,expireAfterWrite或refreshAfterWrite策略的角度來看條目已經空閑的時間。最大持續時間可以從getExpiresAfter(TimeUnit)讀取,並使用setExpiresAfter(long,TimeUnit)進行調整。
如果有需用我們可以通過hottest(int) 和 coldest(int)方法來獲取最有可能命中的數據和最有可能驅逐的數據快照。
測試(Testing)
FakeTicker ticker = new FakeTicker(); // Guava's testlib Cache<Key, Graph> cache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .executor(Runnable::run) .ticker(ticker::read) .maximumSize(10) .build(); cache.put(key, graph); ticker.advance(30, TimeUnit.MINUTES) assertThat(cache.getIfPresent(key), is(nullValue());
測試的時候我們可以使用Caffeine..ticker(ticker)來指定一個時間源,並不需要等到key過期。
FakeTicker這個是guawa test包里面的Ticker,主要用於測試。依賴:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava-testlib</artifactId> <version>23.5-jre</version> </dependency>
常見問題(Faq)
固定數據(Pinning Entries)
固定數據是不能通過驅逐策略去將數據刪除的。當數據是一個有狀態的資源時(如鎖),那么這條數據是非常有用的,你有在客端使用完這個條數據的時候才能刪除該數據。在這種情況下如果驅逐策略將這個條數據刪掉的話,將導致資源泄露。
通過使用權重將該數據的權重設置成0,並且這個條數據不計入maximum size里面。 當緩存達到maximum size 了以后,驅逐策略也會跳過該條數據,不會進行刪除操作。我們還必須自定義一個標准來判斷這個數據是否屬於固定數據。
通過使用Long.MAX_VALUE(大約300年)的值作為key的有效時間,這樣可以將一條數據從過期中排除。自定義到期必須定義,這可以評估條目是否固定。
將數據寫入緩存時我們要指定該數據的權重和到期時間。這可以通過使用cache.asMap()獲取緩存列表后,再來實現引腳和解除綁定。
遞歸調用(Recursive Computations)
在原子操作內執行的加載,計算或回調可能不會寫入緩存。 ConcurrentHashMap不允許這些遞歸寫操作,因為這將有可能導致活鎖(Java 8)或IllegalStateException(Java 9)。
解決方法是異步執行這些操作,例如使用AsyncLoadingCache。在異步這種情況下映射已經建立,value是一個CompletableFuture,並且這些操作是在緩存的原子范圍之外執行的。但是,如果發生無序的依賴鏈,這也有可能導致死鎖。
示例代碼:
package com.xiaolyuh.controller; import com.alibaba.fastjson.JSON; import com.github.benmanes.caffeine.cache.*; import com.google.common.testing.FakeTicker; import com.xiaolyuh.entity.Person; import com.xiaolyuh.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.OptionalLong; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; @RestController public class CaffeineCacheController { @Autowired PersonService personService; Cache<String, Object> manualCache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(10_000) .build(); LoadingCache<String, Object> loadingCache = Caffeine.newBuilder() .maximumSize(10_000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(key -> createExpensiveGraph(key)); AsyncLoadingCache<String, Object> asyncLoadingCache = 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)); private CompletableFuture<Object> createExpensiveGraphAsync(String key, Executor executor) { CompletableFuture<Object> objectCompletableFuture = new CompletableFuture<>(); return objectCompletableFuture; } private Object createExpensiveGraph(String key) { System.out.println("緩存不存在或過期,調用了createExpensiveGraph方法獲取緩存key的值"); if (key.equals("name")) { throw new RuntimeException("調用了該方法獲取緩存key的值的時候出現異常"); } return personService.findOne1(); } @RequestMapping("/testManual") public Object testManual(Person person) { String key = "name1"; Object graph = null; // 根據key查詢一個緩存,如果沒有返回NULL graph = manualCache.getIfPresent(key); // 根據Key查詢一個緩存,如果沒有調用createExpensiveGraph方法,並將返回值保存到緩存。 // 如果該方法返回Null則manualCache.get返回null,如果該方法拋出異常則manualCache.get拋出異常 graph = manualCache.get(key, k -> createExpensiveGraph(k)); // 將一個值放入緩存,如果以前有值就覆蓋以前的值 manualCache.put(key, graph); // 刪除一個緩存 manualCache.invalidate(key); ConcurrentMap<String, Object> map = manualCache.asMap(); System.out.println(map.toString()); return graph; } @RequestMapping("/testLoading") public Object testLoading(Person person) { String key = "name1"; // 采用同步方式去獲取一個緩存和上面的手動方式是一個原理。在build Cache的時候會提供一個createExpensiveGraph函數。 // 查詢並在缺失的情況下使用同步的方式來構建一個緩存 Object graph = loadingCache.get(key); // 獲取組key的值返回一個Map List<String> keys = new ArrayList<>(); keys.add(key); Map<String, Object> graphs = loadingCache.getAll(keys); return graph; } @RequestMapping("/testAsyncLoading") public Object testAsyncLoading(Person person) { String key = "name1"; // 查詢並在缺失的情況下使用異步的方式來構建緩存 CompletableFuture<Object> graph = asyncLoadingCache.get(key); // 查詢一組緩存並在缺失的情況下使用異步的方式來構建緩存 List<String> keys = new ArrayList<>(); keys.add(key); CompletableFuture<Map<String, Object>> graphs = asyncLoadingCache.getAll(keys); // 異步轉同步 loadingCache = asyncLoadingCache.synchronous(); return graph; } @RequestMapping("/testSizeBased") public Object testSizeBased(Person person) { LoadingCache<String, Object> cache = Caffeine.newBuilder() .maximumSize(1) .build(k -> createExpensiveGraph(k)); cache.get("A"); System.out.println(cache.estimatedSize()); cache.get("B"); // 因為執行回收的方法是異步的,所以需要調用該方法,手動觸發一次回收操作。 cache.cleanUp(); System.out.println(cache.estimatedSize()); return ""; } @RequestMapping("/testTimeBased") public Object testTimeBased(Person person) { String key = "name1"; // 用戶測試,一個時間源,返回一個時間值,表示從某個固定但任意時間點開始經過的納秒數。 FakeTicker ticker = new FakeTicker(); // 基於固定的到期策略進行退出 // expireAfterAccess LoadingCache<String, Object> cache1 = Caffeine.newBuilder() .ticker(ticker::read) .expireAfterAccess(5, TimeUnit.SECONDS) .build(k -> createExpensiveGraph(k)); System.out.println("expireAfterAccess:第一次獲取緩存"); cache1.get(key); System.out.println("expireAfterAccess:等待4.9S后,第二次次獲取緩存"); // 直接指定時鍾 ticker.advance(4900, TimeUnit.MILLISECONDS); cache1.get(key); System.out.println("expireAfterAccess:等待0.101S后,第三次次獲取緩存"); ticker.advance(101, TimeUnit.MILLISECONDS); cache1.get(key); // expireAfterWrite LoadingCache<String, Object> cache2 = Caffeine.newBuilder() .ticker(ticker::read) .expireAfterWrite(5, TimeUnit.SECONDS) .build(k -> createExpensiveGraph(k)); System.out.println("expireAfterWrite:第一次獲取緩存"); cache2.get(key); System.out.println("expireAfterWrite:等待4.9S后,第二次次獲取緩存"); ticker.advance(4900, TimeUnit.MILLISECONDS); cache2.get(key); System.out.println("expireAfterWrite:等待0.101S后,第三次次獲取緩存"); ticker.advance(101, TimeUnit.MILLISECONDS); cache2.get(key); // Evict based on a varying expiration policy // 基於不同的到期策略進行退出 LoadingCache<String, Object> cache3 = Caffeine.newBuilder() .ticker(ticker::read) .expireAfter(new Expiry<String, Object>() { @Override public long expireAfterCreate(String key, Object value, long currentTime) { // Use wall clock time, rather than nanotime, if from an external resource return TimeUnit.SECONDS.toNanos(5); } @Override public long expireAfterUpdate(String key, Object graph, long currentTime, long currentDuration) { System.out.println("調用了 expireAfterUpdate:" + TimeUnit.NANOSECONDS.toMillis(currentDuration)); return currentDuration; } @Override public long expireAfterRead(String key, Object graph, long currentTime, long currentDuration) { System.out.println("調用了 expireAfterRead:" + TimeUnit.NANOSECONDS.toMillis(currentDuration)); return currentDuration; } }) .build(k -> createExpensiveGraph(k)); System.out.println("expireAfter:第一次獲取緩存"); cache3.get(key); System.out.println("expireAfter:等待4.9S后,第二次次獲取緩存"); ticker.advance(4900, TimeUnit.MILLISECONDS); cache3.get(key); System.out.println("expireAfter:等待0.101S后,第三次次獲取緩存"); ticker.advance(101, TimeUnit.MILLISECONDS); Object object = cache3.get(key); return object; } @RequestMapping("/testRemoval") public Object testRemoval(Person person) { String key = "name1"; // 用戶測試,一個時間源,返回一個時間值,表示從某個固定但任意時間點開始經過的納秒數。 FakeTicker ticker = new FakeTicker(); // 基於固定的到期策略進行退出 // expireAfterAccess LoadingCache<String, Object> cache = Caffeine.newBuilder() .removalListener((String k, Object graph, RemovalCause cause) -> System.out.printf("Key %s was removed (%s)%n", k, cause)) .ticker(ticker::read) .expireAfterAccess(5, TimeUnit.SECONDS) .build(k -> createExpensiveGraph(k)); System.out.println("第一次獲取緩存"); Object object = cache.get(key); System.out.println("等待6S后,第二次次獲取緩存"); // 直接指定時鍾 ticker.advance(6000, TimeUnit.MILLISECONDS); cache.get(key); System.out.println("手動刪除緩存"); cache.invalidate(key); return object; } @RequestMapping("/testRefresh") public Object testRefresh(Person person) { String key = "name1"; // 用戶測試,一個時間源,返回一個時間值,表示從某個固定但任意時間點開始經過的納秒數。 FakeTicker ticker = new FakeTicker(); // 基於固定的到期策略進行退出 // expireAfterAccess LoadingCache<String, Object> cache = Caffeine.newBuilder() .removalListener((String k, Object graph, RemovalCause cause) -> System.out.printf("執行移除監聽器- Key %s was removed (%s)%n", k, cause)) .ticker(ticker::read) .expireAfterWrite(5, TimeUnit.SECONDS) // 指定在創建緩存或者最近一次更新緩存后經過固定的時間間隔,刷新緩存 .refreshAfterWrite(4, TimeUnit.SECONDS) .build(k -> createExpensiveGraph(k)); System.out.println("第一次獲取緩存"); Object object = cache.get(key); System.out.println("等待4.1S后,第二次次獲取緩存"); // 直接指定時鍾 ticker.advance(4100, TimeUnit.MILLISECONDS); cache.get(key); System.out.println("等待5.1S后,第三次次獲取緩存"); // 直接指定時鍾 ticker.advance(5100, TimeUnit.MILLISECONDS); cache.get(key); return object; } @RequestMapping("/testWriter") public Object testWriter(Person person) { String key = "name1"; // 用戶測試,一個時間源,返回一個時間值,表示從某個固定但任意時間點開始經過的納秒數。 FakeTicker ticker = new FakeTicker(); // 基於固定的到期策略進行退出 // expireAfterAccess LoadingCache<String, Object> cache = Caffeine.newBuilder() .removalListener((String k, Object graph, RemovalCause cause) -> System.out.printf("執行移除監聽器- Key %s was removed (%s)%n", k, cause)) .ticker(ticker::read) .expireAfterWrite(5, TimeUnit.SECONDS) .writer(new CacheWriter<String, Object>() { @Override public void write(String key, Object graph) { // write to storage or secondary cache // 寫入存儲或者二級緩存 System.out.printf("testWriter:write - Key %s was write (%s)%n", key, graph); createExpensiveGraph(key); } @Override public void delete(String key, Object graph, RemovalCause cause) { // delete from storage or secondary cache // 刪除存儲或者二級緩存 System.out.printf("testWriter:delete - Key %s was delete (%s)%n", key, graph); } }) // 指定在創建緩存或者最近一次更新緩存后經過固定的時間間隔,刷新緩存 .refreshAfterWrite(4, TimeUnit.SECONDS) .build(k -> createExpensiveGraph(k)); cache.put(key, personService.findOne1()); cache.invalidate(key); System.out.println("第一次獲取緩存"); Object object = cache.get(key); System.out.println("等待4.1S后,第二次次獲取緩存"); // 直接指定時鍾 ticker.advance(4100, TimeUnit.MILLISECONDS); cache.get(key); System.out.println("等待5.1S后,第三次次獲取緩存"); // 直接指定時鍾 ticker.advance(