Spring Boot集成redis,key自定義生成方式
一)自定義redis key生成策略
@Configuration:表示當前類屬于一個配置類,類似于一個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表示當前類屬于配置類
* @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全局默認配置
* @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緩存的過期時間, 600秒
redisCacheManager.setDefaultExpiration(600L);
return redisCacheManager;
}
}
二)SpringBoot自帶緩存方式
注解說明:
@Cacheable含義:當調(diào)用該注解聲明的方法時,會先從緩存中查找,判斷是否有key相同緩存的數(shù)據(jù),如果有,就直接返回數(shù)據(jù),如果沒有,執(zhí)行方法,然后把返回的數(shù)據(jù)以鍵值的方式存儲到緩存中,方便下次同樣參數(shù)請求時,直接從緩存中返回數(shù)據(jù)。
@Cacheable支持如下幾個參數(shù):
cacheNames:緩存位置的一段名稱,不能為空,和value一個含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個含義。
key:緩存的key,默認為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
keyGenerator:指定key的生成策略。
condition:觸發(fā)條件,滿足條件就加入緩存,默認為空,表示全部都加入緩存,支持SpEL。
@CacheEvict含義:當存在相同key的緩存時,把緩存清空,相當于刪除。
@CacheEvict支持如下幾個參數(shù):
cacheNames:緩存位置的一段名稱,不能為空,和value一個含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個含義。
key:緩存的key,默認為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
condition:觸發(fā)條件,滿足條件就加入緩存,默認為空,表示全部都加入緩存,支持SpEL。
allEntries:true表示清除value中的全部緩存,默認為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中默認都是string
* 在每次請求的時候,都是先根據(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
這負責為緩存中的每個數(shù)據(jù)項生成每個鍵,這些鍵將用于在檢索時查找數(shù)據(jù)項。
此處的默認實現(xiàn)是SimpleKeyGenerator –它使用提供的方法參數(shù)來生成密鑰。這意味著,如果我們有兩個使用相同的緩存名稱和參數(shù)類型集的方法,則很有可能會導致沖突。
它還意味著緩存數(shù)據(jù)可以由另一種方法覆蓋。
3. 自定義密鑰生成器
密鑰生成器只需要實現(xiàn)一個方法:
Object generate(Object object, Method method, Object... params)
如果未正確實現(xiàn)或使用,則可能導致覆蓋緩存數(shù)據(jù)。
讓我們來看看實現(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, "_");
}
}
之后,我們有兩種可能的方式使用它;第一種是在應用程序Config中聲明一個豆。
請務必指出,類必須從緩存配置支持或?qū)崿F(xiàn)緩存配置程序擴展:
@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é)論
在本文中,我們探討了實現(xiàn)自定義春季緩存的密鑰生成器的方法。
與往常一樣,示例的完整源代碼可在 GitHub 上找到。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題
這篇文章主要介紹了mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
解決SpringBoot整合ElasticSearch遇到的連接問題
這篇文章主要介紹了解決SpringBoot整合ElasticSearch遇到的連接問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
maven升級版本后報錯:Blocked mirror for repositories
本文主要介紹了maven升級版本后報錯:Blocked mirror for repositories,文中的解決方法非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-09-09

