1. 程式人生 > >SpringBoot專案開發 - Caffeine本地快取

SpringBoot專案開發 - Caffeine本地快取

轉自
為什麼需要本地快取?在系統中,有些資料,訪問十分頻繁(例如資料字典資料、國家標準行政區域資料),往往把這些資料放入分散式快取中,但為了減少網路傳輸,加快響應速度,快取分散式快取讀壓力,會把這些資料快取到本地JVM中,大多是先取本地快取中,再取分散式快取中的資料

而Caffeine是一個高效能Java 快取庫,使用Java8對Guava快取重寫版本,在Spring Boot 2.0中將取代Guava。
使用spring.cache.cache-names屬性可以在啟動時建立快取
例如,以下application配置建立一個foo和bar快取,最大數量為500,存活時間為10分鐘

spring.cache.cache-names=foo,bar
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

還有一種程式碼實現方式,我在專案中就是使用程式碼方式,如何使用,請往下看…

1. 引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <
artifactId
>
caffeine</artifactId> <version>2.6.2</version> </dependency>

2.新增一個CaffeineConfig配置類,開啟快取@EnableCaching

@Configuration
@EnableCaching //開啟快取
public class CaffeineConfig {
    public static final int DEFAULT_MAXSIZE = 10000;
    public static final int DEFAULT_TTL =
600; /** * 定義cache名稱、超時時長(秒)、最大容量 * 每個cache預設:10秒超時、最多快取50000條資料,需要修改可以在構造方法的引數中指定。 */ public enum Caches{ getUserById(600), //有效期600秒 listCustomers(7200,1000), //有效期2個小時 , 最大容量1000 ; Caches() { } Caches(int ttl) { this.ttl = ttl; } Caches(int ttl, int maxSize) { this.ttl = ttl; this.maxSize = maxSize; } private int maxSize=DEFAULT_MAXSIZE; //最大數量 private int ttl=DEFAULT_TTL; //過期時間(秒) public int getMaxSize() { return maxSize; } public int getTtl() { return ttl; } } /** * 建立基於Caffeine的Cache Manager * @return */ @Bean @Primary public CacheManager caffeineCacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>(); for(Caches c : Caches.values()){ caches.add(new CaffeineCache(c.name(), Caffeine.newBuilder().recordStats() .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS) .maximumSize(c.getMaxSize()) .build()) ); } cacheManager.setCaches(caches); return cacheManager; } }

3.建立一個控制器,使用本地快取,注意@Cacheable,value與上面配置的值對應,key為引數,sync=true表示同步,多個請求會被阻塞

@RestController
@RequestMapping("cache")
public class CacheController {

    @RequestMapping("listCustomers")
    @Cacheable( value = "listCustomers" , key = "#length", sync = true)
    public List<Customer> listCustomers(Long length){
        List<Customer> customers = new ArrayList<>();
        for(int i=1; i <= length ; i ++){
            Customer customer = new Customer(i, "zhuyu"+i, 20 + i, false);
            customers.add(customer);
        }
        return customers;
    }
}

4.啟動專案,訪問上面的方法,效果如下,第一次處理時間為 110ms ,再重新整理幾次頁面只要 1ms,說明後面的請求從本地快取中獲取資料,並返回了
在這裡插入圖片描述
在這裡插入圖片描述

使用本地快取可以加快頁面響應速度,快取分散式快取讀壓力,大量、高併發請求的網站比較適用

Caffeine配置說明:
initialCapacity=[integer]: 初始的快取空間大小
maximumSize=[long]: 快取的最大條數
maximumWeight=[long]: 快取的最大權重
expireAfterAccess=[duration]: 最後一次寫入或訪問後經過固定時間過期
expireAfterWrite=[duration]: 最後一次寫入後經過固定時間過期
refreshAfterWrite=[duration]: 建立快取或者最近一次更新快取後經過固定的時間間隔,重新整理快取
recordStats:開發統計功能

注意:
expireAfterWrite和expireAfterAccess同時存在時,以expireAfterWrite為準。