Java8 Caffeine 本地緩存

一、本地緩存介紹

緩存在日常開發中啓動至關重要的作用,由於是存儲在內存中,數據的讀取速度是非常快的,能大量減少對數據庫的訪問,減少數據庫的壓力。

之前介紹過 Redis 這種 NoSql 作爲緩存組件,它能夠很好的作爲分佈式緩存組件提供多個服務間的緩存,但是 Redis 這種還是需要網絡開銷,增加時耗。本地緩存是直接從本地內存中讀取,沒有網絡開銷,例如秒殺系統或者數據量小的緩存等,比遠程緩存更合適。

二、緩存組件 Caffeine 介紹

按 Caffeine Github 文檔描述,Caffeine 是基於 JAVA 8 的高性能緩存庫。並且在 spring5 (springboot 2.x) 後,spring 官方放棄了 Guava,而使用了性能更優秀的 Caffeine 作爲默認緩存組件。

1、Caffeine 性能

可以通過下圖觀測到,在下面緩存組件中 Caffeine 性能是其中最好的。

2、Caffeine 配置說明

注意:

  • weakValues 和 softValues 不可以同時使用。

  • maximumSize 和 maximumWeight 不可以同時使用。

  • expireAfterWrite 和 expireAfterAccess 同事存在時,以 expireAfterWrite 爲準。

3、軟引用與弱引用

軟引用:如果一個對象只具有軟引用,則內存空間足夠,垃圾回收器就不會回收它;如果內存空間不足了,就會回收這些對象的內存。

弱引用:弱引用的對象擁有更短暫的生命週期。在垃圾回收器線程掃描它所管轄的內存區域的過程中,一旦發現了只具有弱引用的對象,不管當前內存空間足夠與否,都會回收它的內存


 
// 軟引用

Caffeine.newBuilder().softValues().build();


// 弱引用

Caffeine.newBuilder().weakKeys().weakValues().build();

4、填充策略(Population)


Caffeine 爲我們提供了三種填充策略:手動同步異步

4.1 手動加載(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進而對緩存進行一些更改。

4.2 同步加載(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可能會同時加載該組的其餘部分。

4.3 異步加載(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) 方法來替換線程池。

 

5、驅逐策略(eviction)


Caffeine提供三類驅逐策略:基於大小(size-based)基於時間(time-based)基於引用(reference-based)

5.1 基於大小(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) 函數來指定緩存最大權重值。

maximumWeightmaximumSize不可以同時使用

5.2 基於時間(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());

5.3 基於引用(reference-based)


強引用,軟引用,弱引用概念說明請點擊連接,這裏說一下各各引用的區別:

Java 4種引用的級別由高到低依次爲:強引用 > 軟引用 > 弱引用 > 虛引用

引用類型            被垃圾回收時間 用途 生存時間
強引用    從來不會    對象的一般狀態     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()不可以一起使用

6.移除監聽器(Removal)


概念:

驅逐(eviction):由於滿足了某種驅逐策略,後臺自動進行的刪除操作
無效(invalidation):表示由調用方手動刪除緩存
移除(removal):監聽驅逐或無效操作的監聽器

6.1 手動刪除緩存:
在任何時候,您都可能明確地使緩存無效,而不用等待緩存被驅逐。

// individual key
cache.invalidate(key)
// bulk keys
cache.invalidateAll(keys)
// all keys
cache.invalidateAll()

6.2 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)並不會拋出。

7. 刷新(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記錄日誌,並不會拋出。

8.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不能與weakKeysAsyncLoadingCache結合使用

可能的用例(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在緩存中的進行了那些操作的通知。監聽器可以阻止緩存操作,也可以將事件排隊以異步的方式執行。這種類型的監聽器最常用於複製或構建分佈式緩存。

9.統計(Statistics)

Cache<Key, Graph> graphs = Caffeine.newBuilder()
    .maximumSize(10_000)
    .recordStats()
    .build();

使用Caffeine.recordStats(),您可以打開統計信息收集。Cache.stats() 方法返回提供統計信息的CacheStats,如:

  • hitRate():返回命中與請求的比率
  • hitCount(): 返回命中緩存的總數
  • evictionCount():緩存逐出的數量
  • averageLoadPenalty():加載新值所花費的平均時間


10. Cleanup


緩存的刪除策略使用的是惰性刪除和定時刪除,但是我也可以自己調用cache.cleanUp()方法手動觸發一次回收操作。cache.cleanUp()是一個同步方法。

11. 策略(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(5100, TimeUnit.MILLISECONDS);
        cache.get(key);
 
        return object;
    }
 
    @RequestMapping("/testStatistics")
    public Object testStatistics(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)
                // 開啓統計
                .recordStats()
                // 指定在創建緩存或者最近一次更新緩存後經過固定的時間間隔,刷新緩存
                .refreshAfterWrite(4, TimeUnit.SECONDS)
                .build(k -> createExpensiveGraph(k));
 
        for (int i = 0; i < 10; i++) {
            cache.get(key);
            cache.get(key + i);
        }
        // 驅逐是異步操作,所以這裏要手動觸發一次回收操作
        ticker.advance(5100, TimeUnit.MILLISECONDS);
        // 手動觸發一次回收操作
        cache.cleanUp();
 
        System.out.println("緩存命數量:" + cache.stats().hitCount());
        System.out.println("緩存命中率:" + cache.stats().hitRate());
        System.out.println("緩存逐出的數量:" + cache.stats().evictionCount());
        System.out.println("加載新值所花費的平均時間:" + cache.stats().averageLoadPenalty());
 
        return cache.get(key);
    }
 
    @RequestMapping("/testPolicy")
    public Object testPolicy(Person person) {
        FakeTicker ticker = new FakeTicker();
 
        LoadingCache<String, Object> cache = Caffeine.newBuilder()
                .ticker(ticker::read)
                .expireAfterAccess(5, TimeUnit.SECONDS)
                .maximumSize(1)
                .build(k -> createExpensiveGraph(k));
 
        // 在代碼裏面動態的指定最大Size
        cache.policy().eviction().ifPresent(eviction -> {
            eviction.setMaximum(4 * eviction.getMaximum());
        });
 
        cache.get("E");
        cache.get("B");
        cache.get("C");
        cache.cleanUp();
        System.out.println(cache.estimatedSize() + ":" + JSON.toJSON(cache.asMap()).toString());
 
        cache.get("A");
        ticker.advance(100, TimeUnit.MILLISECONDS);
        cache.get("D");
        ticker.advance(100, TimeUnit.MILLISECONDS);
        cache.get("A");
        ticker.advance(100, TimeUnit.MILLISECONDS);
        cache.get("B");
        ticker.advance(100, TimeUnit.MILLISECONDS);
        cache.policy().eviction().ifPresent(eviction -> {
            // 獲取熱點數據Map
            Map<String, Object> hottestMap = eviction.hottest(10);
            // 獲取冷數據Map
            Map<String, Object> coldestMap = eviction.coldest(10);
 
            System.out.println("熱點數據:" + JSON.toJSON(hottestMap).toString());
            System.out.println("冷數據:" + JSON.toJSON(coldestMap).toString());
        });
 
        ticker.advance(3000, TimeUnit.MILLISECONDS);
        // ageOf通過這個方法來查看key的空閒時間
        cache.policy().expireAfterAccess().ifPresent(expiration -> {
 
            System.out.println(JSON.toJSON(expiration.ageOf("A", TimeUnit.MILLISECONDS)));
        });
        return cache.get("name1");
    }
}

 

三、SpringBoot 集成 Caffeine 兩種方式

SpringBoot 有倆種使用 Caffeine 作爲緩存的方式:

  • 方式一:直接引入 Caffeine 依賴,然後使用 Caffeine 方法實現緩存。

  • 方式二:引入 Caffeine 和 Spring Cache 依賴,使用 SpringCache 註解方法實現緩存。

下面將介紹下,這倆中集成方式都是如何實現的。

四、SpringBoot 集成 Caffeine 方式一

1、Maven 引入相關依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
 
    <groupId>mydlq.club</groupId>
    <artifactId>springboot-caffeine-cache-example-1</artifactId>
    <version>0.0.1</version>
    <name>springboot-caffeine-cache-example-1</name>
    <description>Demo project for Spring Boot Cache</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

2、配置緩存配置類

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
 
@Configuration
public class CacheConfig {
 
    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 設置最後一次寫入或訪問後經過固定時間過期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的緩存空間大小
                .initialCapacity(100)
                // 緩存的最大條數
                .maximumSize(1000)
                .build();
    }
 
}

3、定義測試的實體對象

import lombok.Data;
import lombok.ToString;
 
@Data
@ToString
public class UserInfo {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
}

4、定義服務接口類和實現類

UserInfoService

import mydlq.club.example.entity.UserInfo;
 
public interface UserInfoService {
 
    /**
     * 增加用戶信息
     *
     * @param userInfo 用戶信息
     */
    void addUserInfo(UserInfo userInfo);
 
    /**
     * 獲取用戶信息
     *
     * @param id 用戶ID
     * @return 用戶信息
     */
    UserInfo getByName(Integer id);
 
    /**
     * 修改用戶信息
     *
     * @param userInfo 用戶信息
     * @return 用戶信息
     */
    UserInfo updateUserInfo(UserInfo userInfo);
 
    /**
     * 刪除用戶信息
     *
     * @param id 用戶ID
     */
    void deleteById(Integer id);
 
}

UserInfoServiceImpl

import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import mydlq.club.example.entity.UserInfo;
import mydlq.club.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
 
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {
 
    /**
     * 模擬數據庫存儲數據
     */
    private HashMap<Integer, UserInfo> userInfoMap = new HashMap<>();
 
    @Autowired
    Cache<String, Object> caffeineCache;
 
    @Override
    public void addUserInfo(UserInfo userInfo) {
        log.info("create");
        userInfoMap.put(userInfo.getId(), userInfo);
        // 加入緩存
        caffeineCache.put(String.valueOf(userInfo.getId()),userInfo);
    }
 
    @Override
    public UserInfo getByName(Integer id) {
        // 先從緩存讀取
        caffeineCache.getIfPresent(id);
        UserInfo userInfo = (UserInfo) caffeineCache.asMap().get(String.valueOf(id));
        if (userInfo != null){
            return userInfo;
        }
        // 如果緩存中不存在,則從庫中查找
        log.info("get");
        userInfo = userInfoMap.get(id);
        // 如果用戶信息不爲空,則加入緩存
        if (userInfo != null){
            caffeineCache.put(String.valueOf(userInfo.getId()),userInfo);
        }
        return userInfo;
    }
 
    @Override
    public UserInfo updateUserInfo(UserInfo userInfo) {
        log.info("update");
        if (!userInfoMap.containsKey(userInfo.getId())) {
            return null;
        }
        // 取舊的值
        UserInfo oldUserInfo = userInfoMap.get(userInfo.getId());
        // 替換內容
        if (!StringUtils.isEmpty(oldUserInfo.getAge())) {
            oldUserInfo.setAge(userInfo.getAge());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getName())) {
            oldUserInfo.setName(userInfo.getName());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getSex())) {
            oldUserInfo.setSex(userInfo.getSex());
        }
        // 將新的對象存儲,更新舊對象信息
        userInfoMap.put(oldUserInfo.getId(), oldUserInfo);
        // 替換緩存中的值
        caffeineCache.put(String.valueOf(oldUserInfo.getId()),oldUserInfo);
        return oldUserInfo;
    }
 
    @Override
    public void deleteById(Integer id) {
        log.info("delete");
        userInfoMap.remove(id);
        // 從緩存中刪除
        caffeineCache.asMap().remove(String.valueOf(id));
    }
 
}

5、測試的 Controller 類

import mydlq.club.example.entity.UserInfo;
import mydlq.club.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
@RestController
@RequestMapping
public class UserInfoController {
 
    @Autowired
    private UserInfoService userInfoService;
 
    @GetMapping("/userInfo/{id}")
    public Object getUserInfo(@PathVariable Integer id) {
        UserInfo userInfo = userInfoService.getByName(id);
        if (userInfo == null) {
            return "沒有該用戶";
        }
        return userInfo;
    }
 
    @PostMapping("/userInfo")
    public Object createUserInfo(@RequestBody UserInfo userInfo) {
        userInfoService.addUserInfo(userInfo);
        return "SUCCESS";
    }
 
    @PutMapping("/userInfo")
    public Object updateUserInfo(@RequestBody UserInfo userInfo) {
        UserInfo newUserInfo = userInfoService.updateUserInfo(userInfo);
        if (newUserInfo == null){
            return "不存在該用戶";
        }
        return newUserInfo;
    }
 
    @DeleteMapping("/userInfo/{id}")
    public Object deleteUserInfo(@PathVariable Integer id) {
        userInfoService.deleteById(id);
        return "SUCCESS";
    }
 
}

五、SpringBoot 集成 Caffeine 方式二

1、Maven 引入相關依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
 
    <groupId>mydlq.club</groupId>
    <artifactId>springboot-caffeine-cache-example-2</artifactId>
    <version>0.0.1</version>
    <name>springboot-caffeine-cache-example-2</name>
    <description>Demo project for Spring Boot caffeine</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

2、配置緩存配置類

@Configuration
public class CacheConfig {
 
    /**
     * 配置緩存管理器
     *
     * @return 緩存管理器
     */
    @Bean("caffeineCacheManager")
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
                // 設置最後一次寫入或訪問後經過固定時間過期
                .expireAfterAccess(60, TimeUnit.SECONDS)
                // 初始的緩存空間大小
                .initialCapacity(100)
                // 緩存的最大條數
                .maximumSize(1000));
        return cacheManager;
    }
 
}

3、定義測試的實體對象

@Data
@ToString
public class UserInfo {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
}

4、定義服務接口類和實現類

服務接口

import mydlq.club.example.entity.UserInfo;
 
public interface UserInfoService {
 
    /**
     * 增加用戶信息
     *
     * @param userInfo 用戶信息
     */
    void addUserInfo(UserInfo userInfo);
 
    /**
     * 獲取用戶信息
     *
     * @param id 用戶ID
     * @return 用戶信息
     */
    UserInfo getByName(Integer id);
 
    /**
     * 修改用戶信息
     *
     * @param userInfo 用戶信息
     * @return 用戶信息
     */
    UserInfo updateUserInfo(UserInfo userInfo);
 
    /**
     * 刪除用戶信息
     *
     * @param id 用戶ID
     */
    void deleteById(Integer id);
 
}

服務實現類

import lombok.extern.slf4j.Slf4j;
import mydlq.club.example.entity.UserInfo;
import mydlq.club.example.service.UserInfoService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
 
@Slf4j
@Service
@CacheConfig(cacheNames = "caffeineCacheManager")
public class UserInfoServiceImpl implements UserInfoService {
 
    /**
     * 模擬數據庫存儲數據
     */
    private HashMap<Integer, UserInfo> userInfoMap = new HashMap<>();
 
    @Override
    @CachePut(key = "#userInfo.id")
    public void addUserInfo(UserInfo userInfo) {
        log.info("create");
        userInfoMap.put(userInfo.getId(), userInfo);
    }
 
    @Override
    @Cacheable(key = "#id")
    public UserInfo getByName(Integer id) {
        log.info("get");
        return userInfoMap.get(id);
    }
 
    @Override
    @CachePut(key = "#userInfo.id")
    public UserInfo updateUserInfo(UserInfo userInfo) {
        log.info("update");
        if (!userInfoMap.containsKey(userInfo.getId())) {
            return null;
        }
        // 取舊的值
        UserInfo oldUserInfo = userInfoMap.get(userInfo.getId());
        // 替換內容
        if (!StringUtils.isEmpty(oldUserInfo.getAge())) {
            oldUserInfo.setAge(userInfo.getAge());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getName())) {
            oldUserInfo.setName(userInfo.getName());
        }
        if (!StringUtils.isEmpty(oldUserInfo.getSex())) {
            oldUserInfo.setSex(userInfo.getSex());
        }
        // 將新的對象存儲,更新舊對象信息
        userInfoMap.put(oldUserInfo.getId(), oldUserInfo);
        // 返回新對象信息
        return oldUserInfo;
    }
 
    @Override
    @CacheEvict(key = "#id")
    public void deleteById(Integer id) {
        log.info("delete");
        userInfoMap.remove(id);
    }
 
}

5、測試的 Controller 類

import mydlq.club.example.entity.UserInfo;
import mydlq.club.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
@RestController
@RequestMapping
public class UserInfoController {
 
    @Autowired
    private UserInfoService userInfoService;
 
    @GetMapping("/userInfo/{id}")
    public Object getUserInfo(@PathVariable Integer id) {
        UserInfo userInfo = userInfoService.getByName(id);
        if (userInfo == null) {
            return "沒有該用戶";
        }
        return userInfo;
    }
 
    @PostMapping("/userInfo")
    public Object createUserInfo(@RequestBody UserInfo userInfo) {
        userInfoService.addUserInfo(userInfo);
        return "SUCCESS";
    }
 
    @PutMapping("/userInfo")
    public Object updateUserInfo(@RequestBody UserInfo userInfo) {
        UserInfo newUserInfo = userInfoService.updateUserInfo(userInfo);
        if (newUserInfo == null){
            return "不存在該用戶";
        }
        return newUserInfo;
    }
 
    @DeleteMapping("/userInfo/{id}")
    public Object deleteUserInfo(@PathVariable Integer id) {
        userInfoService.deleteById(id);
        return "SUCCESS";
    }
 
}

參考原文地址:

Caffeine 緩存

(很全面)SpringBoot 使用 Caffeine 本地緩存

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章