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í),會(huì)先從緩存中查找,判斷是否有key相同緩存的數(shù)據(jù),如果有,就直接返回?cái)?shù)據(jù),如果沒有,執(zhí)行方法,然后把返回的數(shù)據(jù)以鍵值的方式存儲(chǔ)到緩存中,方便下次同樣參數(shù)請(qǐng)求時(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。
測(cè)試代碼:
package hk.com.cre.process.basic.service.impl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
public class RdisCacheTest {
/**
* 緩存測(cè)試
* 緩存生成規(guī)則: conf:redis:類名方法名參數(shù)hashcode
* 注意: @Cacheable注解生成的類型在redis中默認(rèn)都是string
* 在每次請(qǐng)求的時(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ù)類型集的方法,則很有可能會(huì)導(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è)豆。
請(qǐng)務(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)文章
mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題
這篇文章主要介紹了mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
springboot項(xiàng)目如何設(shè)置session的過期時(shí)間
這篇文章主要介紹了springboot項(xiàng)目如何設(shè)置session的過期時(shí)間,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
學(xué)Java做項(xiàng)目需要學(xué)習(xí)的一些技能
這篇文章主要介紹了學(xué)Java做項(xiàng)目需要學(xué)習(xí)的一些技能,例如JavaSE、Servlet、JSP等,總結(jié)了他們中需要學(xué)習(xí)的東西,都是一些經(jīng)驗(yàn)總結(jié),需要的朋友可以參考下2014-07-07
解決SpringBoot整合ElasticSearch遇到的連接問題
這篇文章主要介紹了解決SpringBoot整合ElasticSearch遇到的連接問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
spring Boot打包部署到遠(yuǎn)程服務(wù)器的tomcat中
這篇文章主要給大家介紹了關(guān)于spring Boot打包部署到遠(yuǎn)程服務(wù)器的tomcat中的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
maven升級(jí)版本后報(bào)錯(cuò):Blocked mirror for repositories
本文主要介紹了maven升級(jí)版本后報(bào)錯(cuò):Blocked mirror for repositories,文中的解決方法非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09
JNDI簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了JNDI簡(jiǎn)介,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08

