天天看點

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,說明後面的請求從本地緩存中擷取資料,并傳回了

SpringBoot項目開發 - Caffeine本地緩存
SpringBoot項目開發 - Caffeine本地緩存

使用本地緩存可以加快頁面響應速度,緩存分布式緩存讀壓力,大量、高并發請求的網站比較适用

Caffeine配置說明:

initialCapacity=[integer]: 初始的緩存空間大小

maximumSize=[long]: 緩存的最大條數

maximumWeight=[long]: 緩存的最大權重

expireAfterAccess=[duration]: 最後一次寫入或通路後經過固定時間過期

expireAfterWrite=[duration]: 最後一次寫入後經過固定時間過期

refreshAfterWrite=[duration]: 建立緩存或者最近一次更新緩存後經過固定的時間間隔,重新整理緩存

recordStats:開發統計功能

注意:

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

繼續閱讀