瞬間學會最潮流的SpringCache配置,caffeine+redisson

概述

在java項目中經(jīng)常有使用緩存的場景,這時候如何使用緩存就很重要了,本文主要介紹spring緩存的選型和實現(xiàn)

什么是合格的緩存

一般業(yè)務緩存需要滿足最低的條件是:
1.有邊界,能定義緩存的大小
2.有過期時間
3.有合理的緩存淘汰策略

緩存選型

毫無疑問本地緩存最合適最強大的是caffeine,功能強大,應用廣泛。
在外部緩存中,redis是比較常用的一個中間件,本身也實現(xiàn)了多種緩存淘汰策略,但是redis作為緩存,太重量級了,需要一整個redis實例作為緩存,并不輕量級。好在有redission這個工具在,redisson使用lua腳本實現(xiàn)了在redis上的有邊界的緩存,并實現(xiàn)了過期時間,空閑等待時間,淘汰策略等。

spring多緩存實現(xiàn)

一個項目中,一般至少會用到本地緩存和redis緩存,所以這里按照上面的選型,使用caffeine+redisson來搭建
配置代碼非常簡單,只需要一個類就完成了。

先引入maven依賴

        <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.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.5.7</version>
        </dependency>
        

下面是java的配置代碼

package com.example.demo.web.vo;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author qiupengjun
 * @Date 2022 11 01 16 33
 **/
@Configuration
public class CommonCacheConfig {
    @Value("${spring.redis.port:0}")
    private int redisPort;
    @Value("${spring.redis.database:0}")
    private int redisDb;
    @Value("${spring.redis.host:0}")
    private String redisHost;
    @Value("${spring.redis.timeout:0}")
    private int redisTimeOut;
    @Value("${spring.redis.password:0}")
    private String redisPassword;
    private enum Caches {
        CAFFEINE_TEST_CACHE(2, 600,300),
        CAFFEINE_TEST_CACHE_1(20, 1800,900),
        REDIS_TEST_CACHE(2, 600,300),
        REDIS_TEST_CACHE_1(20, 1800,900),
        ;
        /** 最大數(shù)量*/
        private final Integer maxSize;
        /** 過期時間 秒*/
        private final Integer ttl;
        /** 最大空閑時間 秒 */
        private Integer maxIdle;
        Caches(Integer maxSize, Integer ttl,Integer maxIdle) {
            this.maxIdle = maxIdle;
            this.maxSize = maxSize;
            this.ttl = ttl;
        }
        Caches(Integer maxSize, Integer ttl) {
            this.maxSize = maxSize;
            this.ttl = ttl;
        }
    }

    @Bean("CAFFEINE_MANAGER")
    @Primary
    public CacheManager buildCaffeineCacheManager() {
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (Caches c : Caches.values()) {
            if(c.name().startsWith("CAFFEINE_")){
                caffeineCaches.add(new CaffeineCache(c.name(),
                                Caffeine.newBuilder()
                                        .recordStats()
                                        .expireAfterWrite(c.ttl, TimeUnit.SECONDS)
                                        .expireAfterAccess(c.maxIdle, TimeUnit.SECONDS)
                                        .maximumSize(c.maxSize)
                                        .build()
                        )
                );
            }
        }

        simpleCacheManager.setCaches(caffeineCaches);
        return simpleCacheManager;
    }

    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson(){
        Config config = new Config();
        //這里使用你的redis地址 以及redis的密碼 和redis要存儲的數(shù)據(jù)庫
        config.useSingleServer()
                .setAddress("redis://"+redisHost+":"+redisPort)
                .setTimeout(redisTimeOut)
                .setPassword(redisPassword)
                .setDatabase(redisDb);
        return Redisson.create(config);
    }

    @Bean("REDISSON_MANAGER")
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<>();
        for (Caches c : Caches.values()) {
            if(c.name().startsWith("REDIS_")){
                //這里要注意單位
                CacheConfig cacheConfig = new CacheConfig(c.ttl*1000,c.maxIdle*1000);
                cacheConfig.setMaxSize(c.maxSize);
                config.put(c.name(),cacheConfig);
            }
        }
        return new RedissonSpringCacheManager(redissonClient, config);
    }
}


可以看到這里有兩個cacheManager的bean,分別對應redisson緩存和caffeine緩存,在Spring里面使用多cacheManager,默認使用帶@Primary注釋的緩存,同時可以通過注解@Cacheable里的cacheManager字段來指定使用緩存。

在這個示例中,我把緩存類型配置放在了enum Caches 這個枚舉內部類中,CAFFEINE_開頭的會在caffeine的cacheManager里面初始化,REDIS_開頭的會在caffeine的cacheManager里面初始化,他們包含了例如最大數(shù)量、過期時間、空閑時間(最后一次讀)等參數(shù)。然后把枚舉的名稱注冊為緩存名。在使用例如@Cacheable類型的緩存注解,字段cacheNames聲明要使用的緩存類型,比如如果使用REDIS_TEST_CACHE,那按配置,緩存最大數(shù)量為2,過期時間600s,300s沒讀取過這個緩存則會去除,如果使用REDIS_TEST_CACHE_1,那按配置,緩存最大數(shù)量為20,過期時間1800s,900s沒讀取過這個緩存則會去除。
示例如下:

  @Cacheable(cacheNames = "REDIS_TEST_CACHE", key = "#root.methodName+':'+#paramTest",cacheManager = "REDISSON_MANAGER")
  public String testCacheRedis(String paramTest){
    return System.currentTimeMillis()+paramTest;
  }
  @Cacheable(cacheNames = "CAFFEINE_TEST_CACHE", key = "#root.methodName+':'+#paramTest",cacheManager = "CAFFEINE_MANAGER")
  public String testCacheCaffeine(String paramTest){
    return System.currentTimeMillis()+paramTest;
  }

在本示例里面cache的關系基本如下圖,通過指定cacheNames和cacheManager來使用緩存


image.png
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容