1. 程式人生 > 其它 >SpringBoot快取註解@Cacheable之自定義key策略及快取失效時間指定

SpringBoot快取註解@Cacheable之自定義key策略及快取失效時間指定

上一篇博文介紹了Spring中快取註解@Cacheable @CacheEvit @CachePut的基本使用,接下來我們將看一下更高階一點的知識點

  • key生成策略
  • 超時時間指定

I. 專案環境

1. 專案依賴

本專案藉助SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA + redis5.0進行開發

開一個web服務用於測試

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

II. 擴充套件知識點

1. key生成策略

對於@Cacheable註解,有兩個引數用於組裝快取的key

  • cacheNames/value: 類似於快取字首
  • key: SpEL表示式,通常根據傳參來生成最終的快取key

預設的redisKey = cacheNames::key (注意中間的兩個冒號)

/**
 * 沒有指定key時,採用預設策略 {@link org.springframework.cache.interceptor.SimpleKeyGenerator } 生成key
 * <p>
 * 對應的key為: k1::id
 * value --> 等同於 cacheNames
 * @param id
 * @return
 */
@Cacheable(value = "k1")
public String key1(int id) {
    return "defaultKey:" + id;
}

快取key預設採用SimpleKeyGenerator來生成,比如上面的呼叫,如果id=1, 那麼對應的快取key為 k1::1

如果沒有引數,或者多個引數呢?

/**
 * redis_key :  k2::SimpleKey[]
 *
 * @return
 */
@Cacheable(value = "k0")
public String key0() {
    return "key0";
}

/**
 * redis_key :  k2::SimpleKey[id,id2]
 *
 * @param id
 * @param id2
 * @return
 */
@Cacheable(value = "k2")
public String key2(Integer id, Integer id2) {
    return "key1" + id + "_" + id2;
}


@Cacheable(value = "k3")
public String key3(Map map) {
    return "key3" + map;
}

然後寫一個測試case

@RestController
@RequestMapping(path = "extend")
public class ExtendRest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ExtendDemo extendDemo;

    @GetMapping(path = "default")
    public Map<String, Object> key(int id) {
        Map<String, Object> res = new HashMap<>();
        res.put("key0", extendDemo.key0());
        res.put("key1", extendDemo.key1(id));
        res.put("key2", extendDemo.key2(id, id));
        res.put("key3", extendDemo.key3(res));

        // 這裡將快取key都撈出來
        Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<byte[]> sets = connection.keys("k*".getBytes());
            Set<String> ans = new HashSet<>();
            for (byte[] b : sets) {
                ans.add(new String(b));
            }
            return ans;
        });

        res.put("keys", keys);
        return res;
    }
}

訪問之後,輸出結果如下

{
    "key1": "defaultKey:1",
    "key2": "key11_1",
    "key0": "key0",
    "key3": "key3{key1=defaultKey:1, key2=key11_1, key0=key0}",
    "keys": [
        "k2::SimpleKey [1,1]",
        "k1::1",
        "k3::{key1=defaultKey:1, key2=key11_1, key0=key0}",
        "k0::SimpleKey []"
    ]
}

小結一下

  • 單引數:cacheNames::arg
  • 無引數: cacheNames::SimpleKey [], 後面使用 SimpleKey []來補齊
  • 多引數: cacheNames::SimpleKey [arg1, arg2...]
  • 非基礎物件:cacheNames::obj.toString()

2. 自定義key生成策略

如果希望使用自定義的key生成策略,只需繼承KeyGenerator,並宣告為一個bean

@Component("selfKeyGenerate")
public static class SelfKeyGenerate implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return target.getClass().getSimpleName() + "#" + method.getName() + "(" + JSON.toJSONString(params) + ")";
    }
}

然後在使用的地方,利用註解中的keyGenerator來指定key生成策略

/**
 * 對應的redisKey 為: get  vv::ExtendDemo#selfKey([id])
 *
 * @param id
 * @return
 */
@Cacheable(value = "vv", keyGenerator = "selfKeyGenerate")
public String selfKey(int id) {
    return "selfKey:" + id + " --> " + UUID.randomUUID().toString();
}

測試用例

@GetMapping(path = "self")
public Map<String, Object> self(int id) {
    Map<String, Object> res = new HashMap<>();
    res.put("self", extendDemo.selfKey(id));
    Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
        Set<byte[]> sets = connection.keys("vv*".getBytes());
        Set<String> ans = new HashSet<>();
        for (byte[] b : sets) {
            ans.add(new String(b));
        }
        return ans;
    });
    res.put("keys", keys);
    return res;
}

快取key放在了返回結果的keys中,輸出如下,和預期的一致

{
    "keys": [
        "vv::ExtendDemo#selfKey([1])"
    ],
    "self": "selfKey:1 --> f5f8aa2a-0823-42ee-99ec-2c40fb0b9338"
}

3. 快取失效時間

以上所有的快取都沒有設定失效時間,實際的業務場景中,不設定失效時間的場景有;但更多的都需要設定一個ttl,對於Spring的快取註解,原生沒有額外提供一個指定ttl的配置,如果我們希望指定ttl,可以通過RedisCacheManager來完成

private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
    // 設定 json 序列化
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
    redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
            RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).
            // 設定過期時間
            entryTtl(Duration.ofSeconds(seconds));

    return redisCacheConfiguration;
}

上面是一個設定RedisCacheConfiguration的方法,其中有兩個點

  • 序列化方式:採用json對快取內容進行序列化
  • 失效時間:根據傳參來設定失效時間

如果希望針對特定的key進行定製化的配置的話,可以如下操作

private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
    Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(8);
    // 自定義設定快取時間
    // 這個k0 表示的是快取註解中的 cacheNames/value
    redisCacheConfigurationMap.put("k0", this.getRedisCacheConfigurationWithTtl(60 * 60));
    return redisCacheConfigurationMap;
}

最後就是定義我們需要的RedisCacheManager

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    return new RedisCacheManager(
            RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
            // 預設策略,未配置的 key 會使用這個
            this.getRedisCacheConfigurationWithTtl(60),
            // 指定 key 策略
            this.getRedisCacheConfigurationMap()
    );
}

在前面的測試case基礎上,新增返回ttl的資訊

private Object getTtl(String key) {
    return redisTemplate.execute(new RedisCallback() {
        @Override
        public Object doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.ttl(key.getBytes());
        }
    });
}

@GetMapping(path = "default")
public Map<String, Object> key(int id) {
    Map<String, Object> res = new HashMap<>();
    res.put("key0", extendDemo.key0());
    res.put("key1", extendDemo.key1(id));
    res.put("key2", extendDemo.key2(id, id));
    res.put("key3", extendDemo.key3(res));

    Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
        Set<byte[]> sets = connection.keys("k*".getBytes());
        Set<String> ans = new HashSet<>();
        for (byte[] b : sets) {
            ans.add(new String(b));
        }
        return ans;
    });

    res.put("keys", keys);

    Map<String, Object> ttl = new HashMap<>(8);
    for (String key : keys) {
        ttl.put(key, getTtl(key));
    }
    res.put("ttl", ttl);
    return res;
}

返回結果如下,注意返回的ttl失效時間

4. 自定義失效時間擴充套件

雖然上面可以實現失效時間指定,但是用起來依然不是很爽,要麼是全域性設定為統一的失效時間;要麼就是在程式碼裡面硬編碼指定,失效時間與快取定義的地方隔離,這就很不直觀了

接下來介紹一種,直接在註解中,設定失效時間的case

如下面的使用case

/**
 * 通過自定義的RedisCacheManager, 對value進行解析,=後面的表示失效時間
 * @param key
 * @return
 */
@Cacheable(value = "ttl=30")
public String ttl(String key) {
    return "k_" + key;
}

自定義的策略如下:

  • value中,等號左邊的為cacheName, 等號右邊的為失效時間

要實現這個邏輯,可以擴充套件一個自定義的RedisCacheManager,如

public class TtlRedisCacheManager extends RedisCacheManager {
    public TtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] cells = StringUtils.delimitedListToStringArray(name, "=");
        name = cells[0];
        if (cells.length > 1) {
            long ttl = Long.parseLong(cells[1]);
            // 根據傳參設定快取失效時間
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
        }
        return super.createRedisCache(name, cacheConfig);
    }
}

重寫createRedisCache邏輯, 根據name解析出失效時間;

註冊使用方式與上面一致,宣告為Spring的bean物件

@Primary
@Bean
public RedisCacheManager ttlCacheManager(RedisConnectionFactory redisConnectionFactory) {
    return new TtlRedisCacheManager(RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory),
            // 預設快取配置
            this.getRedisCacheConfigurationWithTtl(60));
}

測試case如下

@GetMapping(path = "ttl")
public Map ttl(String k) {
    Map<String, Object> res = new HashMap<>();
    res.put("execute", extendDemo.ttl(k));
    res.put("ttl", getTtl("ttl::" + k));
    return res;
}

驗證結果如下

5. 小結

到此基本上將Spring中快取註解的常用姿勢都介紹了一下,無論是幾個註解的使用case,還是自定義的key策略,失效時間指定,單純從使用的角度來看,基本能滿足我們的日常需求場景

下面是針對快取註解的一個知識點抽象

快取註解

  • @Cacheable: 快取存在,則從快取取;否則執行方法,並將返回結果寫入快取
  • @CacheEvit: 失效快取
  • @CachePut: 更新快取
  • @Caching: 都註解組合

配置引數

  • cacheNames/value: 可以理解為快取字首
  • key: 可以理解為快取key的變數,支援SpEL表示式
  • keyGenerator: key組裝策略
  • condition/unless: 快取是否可用的條件

預設快取ke策略y

下面的cacheNames為註解中定義的快取字首,兩個分號固定

  • 單引數:cacheNames::arg
  • 無引數: cacheNames::SimpleKey [], 後面使用 SimpleKey []來補齊
  • 多引數: cacheNames::SimpleKey [arg1, arg2...]
  • 非基礎物件:cacheNames::obj.toString()

快取失效時間

失效時間,本文介紹了兩種方式,一個是集中式的配置,通過設定RedisCacheConfiguration來指定ttl時間

另外一個是擴充套件RedisCacheManager類,實現自定義的cacheNames擴充套件解析

Spring快取註解知識點到此告一段落,我是一灰灰,歡迎關注長草的公眾號一灰灰blog

III. 不能錯過的原始碼和相關知識點

0. 專案

系列博文

原始碼

1. 一灰灰Blog

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激

下面一灰灰的個人部落格,記錄所有學習和工作中的博文,歡迎大家前去逛逛