Spring Boot集成redis,key自定義生成方式
一)自定義redis key生成策略
@Configuration:表示當(dāng)前類屬于一個(gè)配置類,類似于一個(gè)spring.cfg.xml。
@EnableCaching:表示支持啟用緩存。
自定義配置源碼:
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.core.RedisTemplate;
import com.alibaba.fastjson.JSON;
/**
* redis配置工具類
* @Configuration表示當(dāng)前類屬于配置類
* @EnableCaching表示支持緩存
* @author ouyangjun
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* redis key生成策略
* target: 類
* method: 方法
* params: 參數(shù)
* @return KeyGenerator
* 注意: 該方法只是聲明了key的生成策略,還未被使用,需在@Cacheable注解中指定keyGenerator
* 如: @Cacheable(value = "key", keyGenerator = "cacheKeyGenerator")
*/
@Bean
public KeyGenerator cacheKeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
// 由于參數(shù)可能不同, hashCode肯定不一樣, 緩存的key也需要不一樣
sb.append(JSON.toJSONString(obj).hashCode());
}
return sb.toString();
};
}
/**
* redis全局默認(rèn)配置
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setUsePrefix(true);
// key緩存的前綴,以conf開頭
RedisCachePrefix cachePrefix = new RedisPrefix("conf");
redisCacheManager.setCachePrefix(cachePrefix);
// key緩存的過期時(shí)間, 600秒
redisCacheManager.setDefaultExpiration(600L);
return redisCacheManager;
}
}
二)SpringBoot自帶緩存方式
注解說明:
@Cacheable含義:當(dāng)調(diào)用該注解聲明的方法時(shí),會先從緩存中查找,判斷是否有key相同緩存的數(shù)據(jù),如果有,就直接返回?cái)?shù)據(jù),如果沒有,執(zhí)行方法,然后把返回的數(shù)據(jù)以鍵值的方式存儲到緩存中,方便下次同樣參數(shù)請求時(shí),直接從緩存中返回?cái)?shù)據(jù)。
@Cacheable支持如下幾個(gè)參數(shù):
cacheNames:緩存位置的一段名稱,不能為空,和value一個(gè)含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個(gè)含義。
key:緩存的key,默認(rèn)為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
keyGenerator:指定key的生成策略。
condition:觸發(fā)條件,滿足條件就加入緩存,默認(rèn)為空,表示全部都加入緩存,支持SpEL。
@CacheEvict含義:當(dāng)存在相同key的緩存時(shí),把緩存清空,相當(dāng)于刪除。
@CacheEvict支持如下幾個(gè)參數(shù):
cacheNames:緩存位置的一段名稱,不能為空,和value一個(gè)含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個(gè)含義。
key:緩存的key,默認(rèn)為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
condition:觸發(fā)條件,滿足條件就加入緩存,默認(rèn)為空,表示全部都加入緩存,支持SpEL。
allEntries:true表示清除value中的全部緩存,默認(rèn)為false。
測試代碼:
package hk.com.cre.process.basic.service.impl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
public class RdisCacheTest {
/**
* 緩存測試
* 緩存生成規(guī)則: conf:redis:類名方法名參數(shù)hashcode
* 注意: @Cacheable注解生成的類型在redis中默認(rèn)都是string
* 在每次請求的時(shí)候,都是先根據(jù)key到redis查詢是否存在,如不存在則執(zhí)行方法中的代碼
*/
@Cacheable(cacheNames = "redis", keyGenerator = "cacheKeyGenerator")
public String getRedisString(String param1, String param2) {
return param1+":"+param2;
}
/**
* 清除緩存
*/
@CacheEvict(cacheNames = "redis", allEntries = true)
public String cleanCache() {
return "success";
}
}
Spring Cache – KeyGenerator自定義rediskey
1. 概述
在此教程中,我們將演示如何使用 Spring Cache 創(chuàng)建自定義密鑰生成器。
2. KeyGenerator
這負(fù)責(zé)為緩存中的每個(gè)數(shù)據(jù)項(xiàng)生成每個(gè)鍵,這些鍵將用于在檢索時(shí)查找數(shù)據(jù)項(xiàng)。
此處的默認(rèn)實(shí)現(xiàn)是SimpleKeyGenerator –它使用提供的方法參數(shù)來生成密鑰。這意味著,如果我們有兩個(gè)使用相同的緩存名稱和參數(shù)類型集的方法,則很有可能會導(dǎo)致沖突。
它還意味著緩存數(shù)據(jù)可以由另一種方法覆蓋。
3. 自定義密鑰生成器
密鑰生成器只需要實(shí)現(xiàn)一個(gè)方法:
Object generate(Object object, Method method, Object... params)
如果未正確實(shí)現(xiàn)或使用,則可能導(dǎo)致覆蓋緩存數(shù)據(jù)。
讓我們來看看實(shí)現(xiàn):
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_"
+ method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}
之后,我們有兩種可能的方式使用它;第一種是在應(yīng)用程序Config中聲明一個(gè)豆。
請務(wù)必指出,類必須從緩存配置支持或?qū)崿F(xiàn)緩存配置程序擴(kuò)展:
@EnableCaching
@Configuration
public class ApplicationConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Cache booksCache = new ConcurrentMapCache("books");
cacheManager.setCaches(Arrays.asList(booksCache));
return cacheManager;
}
@Bean("customKeyGenerator")
public KeyGenerator keyGenerator() {
return new CustomKeyGenerator();
}
}
第二種方法是將其用于特定方法:
@Component
public class BookService {
@Cacheable(value = "books", keyGenerator = "customKeyGenerator")
public List<Book> getBooks() {
List<Book> books = new ArrayList<>();
books.add(new Book("The Counterfeiters", "André Gide"));
books.add(new Book("Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
return books;
}
}
4. 結(jié)論
在本文中,我們探討了實(shí)現(xiàn)自定義春季緩存的密鑰生成器的方法。
與往常一樣,示例的完整源代碼可在 GitHub 上找到。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java數(shù)組擴(kuò)容縮容與拷貝的實(shí)現(xiàn)和原理
這篇文章主要帶大家學(xué)習(xí)數(shù)組的擴(kuò)容、縮容及拷貝,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Springcloud Bus消息總線原理是實(shí)現(xiàn)詳解
Spring Cloud Bus 使用輕量級的消息代理來連接微服務(wù)架構(gòu)中的各個(gè)服務(wù),可以將其用于廣播狀態(tài)更改(例如配置中心配置更改)或其他管理指令,本文將對其用法進(jìn)行詳細(xì)介紹2022-09-09
Springboot整合ActiveMQ實(shí)現(xiàn)消息隊(duì)列的過程淺析
昨天仔細(xì)研究了activeMQ消息隊(duì)列,也遇到了些坑,下面這篇文章主要給大家介紹了關(guān)于SpringBoot整合ActiveMQ的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之樹
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之樹,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java數(shù)據(jù)結(jié)構(gòu)的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05

