本地緩存之王,Caffeine 保姆級教程

一、Caffeine 介紹

1、緩存介紹

緩存 (Cache) 在代碼世界中無處不在。從底層的 CPU 多級緩存,到客戶端的頁面緩存,處處都存在着緩存的身影。緩存從本質上來說,是一種空間換時間的手段,通過對數據進行一定的空間安排,使得下次進行數據訪問時起到加速的效果。

就 Java 而言,其常用的緩存解決方案有很多,例如數據庫緩存框架 EhCache,分佈式緩存 Memcached 等,這些緩存方案實際上都是爲了提升吞吐效率,避免持久層壓力過大。

對於常見緩存類型而言,可以分爲本地緩存以及分佈式緩存兩種,Caffeine 就是一種優秀的本地緩存,而 Redis 可以用來做分佈式緩存

2、Caffeine 介紹

Caffeine 官方:

  • https://github.com/ben-manes/caffeine

Caffeine 是基於 Java 1.8 的高性能本地緩存庫,由 Guava 改進而來,而且在 Spring5 開始的默認緩存實現就將 Caffeine 代替原來的 Google Guava,官方說明指出,其緩存命中率已經接近最優值。實際上 Caffeine 這樣的本地緩存和 ConcurrentMap 很像,即支持併發,並且支持 O(1) 時間複雜度的數據存取。二者的主要區別在於:

因此,一種更好的理解方式是:Cache 是一種帶有存儲和移除策略的 Map。

二、Caffeine 基礎

使用 Caffeine,需要在工程中引入如下依賴

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <!--https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeinez找最新版-->
    <version>3.0.5</version>
</dependency>

1、緩存加載策略

1.1 Cache 手動創建

最普通的一種緩存,無需指定加載方式,需要手動調用put()進行加載。需要注意的是put()方法對於已存在的 key 將進行覆蓋,這點和 Map 的表現是一致的。在獲取緩存值時,如果想要在緩存值不存在時,原子地將值寫入緩存,則可以調用get(key, k -> value)方法,該方法將避免寫入競爭。調用invalidate()方法,將手動移除緩存。

在多線程情況下,當使用get(key, k -> value)時,如果有另一個線程同時調用本方法進行競爭,則後一線程會被阻塞,直到前一線程更新緩存完成;而若另一線程調用getIfPresent()方法,則會立即返回 null,不會被阻塞。

Cache<Object, Object> cache = Caffeine.newBuilder()
          //初始數量
          .initialCapacity(10)
          //最大條數
          .maximumSize(10)
          //expireAfterWrite和expireAfterAccess同時存在時,以expireAfterWrite爲準
          //最後一次寫操作後經過指定時間過期
          .expireAfterWrite(1, TimeUnit.SECONDS)
          //最後一次讀或寫操作後經過指定時間過期
          .expireAfterAccess(1, TimeUnit.SECONDS)
          //監聽緩存被移除
          .removalListener((key, val, removalCause) -> { })
          //記錄命中
          .recordStats()
          .build();

  cache.put("1","張三");
  //張三
  System.out.println(cache.getIfPresent("1"));
  //存儲的是默認值
  System.out.println(cache.get("2",o -> "默認值"));
1.2 Loading Cache 自動創建

LoadingCache 是一種自動加載的緩存。其和普通緩存不同的地方在於,當緩存不存在 / 緩存已過期時,若調用get()方法,則會自動調用CacheLoader.load()方法加載最新值。調用getAll()方法將遍歷所有的 key 調用 get(),除非實現了CacheLoader.loadAll()方法。使用 LoadingCache 時,需要指定 CacheLoader,並實現其中的load()方法供緩存缺失時自動加載。

在多線程情況下,當兩個線程同時調用get(),則後一線程將被阻塞,直至前一線程更新緩存完成。

LoadingCache<String, String> loadingCache = Caffeine.newBuilder()
        //創建緩存或者最近一次更新緩存後經過指定時間間隔,刷新緩存;refreshAfterWrite僅支持LoadingCache
        .refreshAfterWrite(10, TimeUnit.SECONDS)
        .expireAfterWrite(10, TimeUnit.SECONDS)
        .expireAfterAccess(10, TimeUnit.SECONDS)
        .maximumSize(10)
        //根據key查詢數據庫裏面的值,這裏是個lamba表達式
        .build(key -> new Date().toString());
1.3 Async Cache 異步獲取

AsyncCache 是 Cache 的一個變體,其響應結果均爲CompletableFuture,通過這種方式,AsyncCache 對異步編程模式進行了適配。默認情況下,緩存計算使用ForkJoinPool.commonPool()作爲線程池,如果想要指定線程池,則可以覆蓋並實現Caffeine.executor(Executor)方法。synchronous()提供了阻塞直到異步緩存生成完畢的能力,它將以 Cache 進行返回。

在多線程情況下,當兩個線程同時調用get(key, k -> value),則會返回同一個CompletableFuture對象。由於返回結果本身不進行阻塞,可以根據業務設計自行選擇阻塞等待或者非阻塞。

AsyncLoadingCache<String, String> asyncLoadingCache = Caffeine.newBuilder()
        //創建緩存或者最近一次更新緩存後經過指定時間間隔刷新緩存;僅支持LoadingCache
        .refreshAfterWrite(1, TimeUnit.SECONDS)
        .expireAfterWrite(1, TimeUnit.SECONDS)
        .expireAfterAccess(1, TimeUnit.SECONDS)
        .maximumSize(10)
        //根據key查詢數據庫裏面的值
        .buildAsync(key -> {
            Thread.sleep(1000);
            return new Date().toString();
        });

//異步緩存返回的是CompletableFuture
CompletableFuture<String> future = asyncLoadingCache.get("1");
future.thenAccept(System.out::println);

2、驅逐策略

驅逐策略在創建緩存的時候進行指定。常用的有基於容量的驅逐和基於時間的驅逐。

基於容量的驅逐需要指定緩存容量的最大值,當緩存容量達到最大時,Caffeine 將使用 LRU 策略對緩存進行淘汰;基於時間的驅逐策略如字面意思,可以設置在最後訪問 / 寫入一個緩存經過指定時間後,自動進行淘汰。

驅逐策略可以組合使用,任意驅逐策略生效後,該緩存條目即被驅逐。

Caffeine 有 4 種緩存淘汰設置

@Slf4j
public class CacheTest {
    /**
     * 緩存大小淘汰
     */
    @Test
    public void maximumSizeTest() throws InterruptedException {
        Cache<Integer, Integer> cache = Caffeine.newBuilder()
                //超過10個後會使用W-TinyLFU算法進行淘汰
                .maximumSize(10)
                .evictionListener((key, val, removalCause) -> {
                    log.info("淘汰緩存:key:{} val:{}", key, val);
                })
                .build();

        for (int i = 1; i < 20; i++) {
            cache.put(i, i);
        }
        Thread.sleep(500);//緩存淘汰是異步的

        // 打印還沒被淘汰的緩存
        System.out.println(cache.asMap());
    }

    /**
     * 權重淘汰
     */
    @Test
    public void maximumWeightTest() throws InterruptedException {
        Cache<Integer, Integer> cache = Caffeine.newBuilder()
                //限制總權重,若所有緩存的權重加起來>總權重就會淘汰權重小的緩存
                .maximumWeight(100)
                .weigher((Weigher<Integer, Integer>) (key, value) -> key)
                .evictionListener((key, val, removalCause) -> {
                    log.info("淘汰緩存:key:{} val:{}", key, val);
                })
                .build();

        //總權重其實是=所有緩存的權重加起來
        int maximumWeight = 0;
        for (int i = 1; i < 20; i++) {
            cache.put(i, i);
            maximumWeight += i;
        }
        System.out.println("總權重=" + maximumWeight);
        Thread.sleep(500);//緩存淘汰是異步的

        // 打印還沒被淘汰的緩存
        System.out.println(cache.asMap());
    }


    /**
     * 訪問後到期(每次訪問都會重置時間,也就是說如果一直被訪問就不會被淘汰)
     */
    @Test
    public void expireAfterAccessTest() throws InterruptedException {
        Cache<Integer, Integer> cache = Caffeine.newBuilder()
                .expireAfterAccess(1, TimeUnit.SECONDS)
                //可以指定調度程序來及時刪除過期緩存項,而不是等待Caffeine觸發定期維護
                //若不設置scheduler,則緩存會在下一次調用get的時候纔會被動刪除
                .scheduler(Scheduler.systemScheduler())
                .evictionListener((key, val, removalCause) -> {
                    log.info("淘汰緩存:key:{} val:{}", key, val);

                })
                .build();
        cache.put(1, 2);
        System.out.println(cache.getIfPresent(1));
        Thread.sleep(3000);
        System.out.println(cache.getIfPresent(1));//null
    }

    /**
     * 寫入後到期
     */
    @Test
    public void expireAfterWriteTest() throws InterruptedException {
        Cache<Integer, Integer> cache = Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.SECONDS)
                //可以指定調度程序來及時刪除過期緩存項,而不是等待Caffeine觸發定期維護
                //若不設置scheduler,則緩存會在下一次調用get的時候纔會被動刪除
                .scheduler(Scheduler.systemScheduler())
                .evictionListener((key, val, removalCause) -> {
                    log.info("淘汰緩存:key:{} val:{}", key, val);
                })
                .build();
        cache.put(1, 2);
        Thread.sleep(3000);
        System.out.println(cache.getIfPresent(1));//null
    }
}

3、刷新機制

refreshAfterWrite()表示 x 秒後自動刷新緩存的策略可以配合淘汰策略使用,注意的是刷新機制只支持 LoadingCache 和 AsyncLoadingCache

private static int NUM = 0;

@Test
public void refreshAfterWriteTest() throws InterruptedException {
    LoadingCache<Integer, Integer> cache = Caffeine.newBuilder()
            .refreshAfterWrite(1, TimeUnit.SECONDS)
            //模擬獲取數據,每次獲取就自增1
            .build(integer -> ++NUM);

    //獲取ID=1的值,由於緩存裏還沒有,所以會自動放入緩存
    System.out.println(cache.get(1));// 1

    // 延遲2秒後,理論上自動刷新緩存後取到的值是2
    // 但其實不是,值還是1,因爲refreshAfterWrite並不是設置了n秒後重新獲取就會自動刷新
    // 而是x秒後&&第二次調用getIfPresent的時候纔會被動刷新
    Thread.sleep(2000);
    System.out.println(cache.getIfPresent(1));// 1

    //此時纔會刷新緩存,而第一次拿到的還是舊值
    System.out.println(cache.getIfPresent(1));// 2
}

4、統計

LoadingCache<String, String> cache = Caffeine.newBuilder()
        //創建緩存或者最近一次更新緩存後經過指定時間間隔,刷新緩存;refreshAfterWrite僅支持LoadingCache
        .refreshAfterWrite(1, TimeUnit.SECONDS)
        .expireAfterWrite(1, TimeUnit.SECONDS)
        .expireAfterAccess(1, TimeUnit.SECONDS)
        .maximumSize(10)
        //開啓記錄緩存命中率等信息
        .recordStats()
        //根據key查詢數據庫裏面的值
        .build(key -> {
            Thread.sleep(1000);
            return new Date().toString();
        });


cache.put("1""shawn");
cache.get("1");

/*
 * hitCount :命中的次數
 * missCount:未命中次數
 * requestCount:請求次數
 * hitRate:命中率
 * missRate:丟失率
 * loadSuccessCount:成功加載新值的次數
 * loadExceptionCount:失敗加載新值的次數
 * totalLoadCount:總條數
 * loadExceptionRate:失敗加載新值的比率
 * totalLoadTime:全部加載時間
 * evictionCount:丟失的條數
 */
System.out.println(cache.stats());

5、總結

上述一些策略在創建時都可以進行自由組合,一般情況下有兩種方法

三、SpringBoot 整合 Caffeine

1、@Cacheable 相關注解

1.1 相關依賴

如果要使用@Cacheable註解,需要引入相關依賴,並在任一配置類文件上添加@EnableCaching註解

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
1.2 常用註解
@Caching(cacheable = @Cacheable("CacheConstants.GET_USER"),
         evict = {@CacheEvict("CacheConstants.GET_DYNAMIC",allEntries = true)}
public User find(Integer id) {
    return null;
}
1.3 常用註解屬性
1.4 緩存同步模式

sync 開啓或關閉,在 Cache 和 LoadingCache 中的表現是不一致的:

2、實戰

2.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>
</dependency>
2.2 緩存常量 CacheConstants

創建緩存常量類,把公共的常量提取一層,複用,這裏也可以通過配置文件加載這些數據,例如@ConfigurationProperties@Value

public class CacheConstants {
    /**
     * 默認過期時間(配置類中我使用的時間單位是秒,所以這裏如 3*60 爲3分鐘)
     */
    public static final int DEFAULT_EXPIRES = 3 * 60;
    public static final int EXPIRES_5_MIN = 5 * 60;
    public static final int EXPIRES_10_MIN = 10 * 60;

    public static final String GET_USER = "GET:USER";
    public static final String GET_DYNAMIC = "GET:DYNAMIC";

}
2.3 緩存配置類 CacheConfig
@Configuration
@EnableCaching
public class CacheConfig {
    /**
     * Caffeine配置說明:
     * initialCapacity=[integer]: 初始的緩存空間大小
     * maximumSize=[long]: 緩存的最大條數
     * maximumWeight=[long]: 緩存的最大權重
     * expireAfterAccess=[duration]: 最後一次寫入或訪問後經過固定時間過期
     * expireAfterWrite=[duration]: 最後一次寫入後經過固定時間過期
     * refreshAfterWrite=[duration]: 創建緩存或者最近一次更新緩存後經過固定的時間間隔,刷新緩存
     * weakKeys: 打開key的弱引用
     * weakValues:打開value的弱引用
     * softValues:打開value的軟引用
     * recordStats:開發統計功能
     * 注意:
     * expireAfterWrite和expireAfterAccess同事存在時,以expireAfterWrite爲準。
     * maximumSize和maximumWeight不可以同時使用
     * weakValues和softValues不可以同時使用
     */
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<CaffeineCache> list = new ArrayList<>();
        //循環添加枚舉類中自定義的緩存,可以自定義
        for (CacheEnum cacheEnum : CacheEnum.values()) {
            list.add(new CaffeineCache(cacheEnum.getName(),
                    Caffeine.newBuilder()
                            .initialCapacity(50)
                            .maximumSize(1000)
                            .expireAfterAccess(cacheEnum.getExpires(), TimeUnit.SECONDS)
                            .build()));
        }
        cacheManager.setCaches(list);
        return cacheManager;
    }
}
2.4 調用緩存

這裏要注意的是 Cache 和 @Transactional 一樣也使用了代理,類內調用將失效

/**
 * value:緩存key的前綴。
 * key:緩存key的後綴。
 * sync:設置如果緩存過期是不是隻放一個請求去請求數據庫,其他請求阻塞,默認是false(根據個人需求)。
 * unless:不緩存空值,這裏不使用,會報錯
 * 查詢用戶信息類
 * 如果需要加自定義字符串,需要用單引號
 * 如果查詢爲null,也會被緩存
 */
@Cacheable(value = CacheConstants.GET_USER,key = "'user'+#userId",sync = true)
@CacheEvict
public UserEntity getUserByUserId(Integer userId){
    UserEntity userEntity = userMapper.findById(userId);
    System.out.println("查詢了數據庫");
    return userEntity;
}

來源:blog.csdn.net/lemon_TT/article/

details/122905113

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/VmweTqDD2P3DKuuANGORig