SpringBoot集成Redis使用Cache緩存的實現(xiàn)方法
使用SpringBoot集成Redis使用Cache緩存只要配置相應(yīng)的配置類,然后使用Cache注解就能實現(xiàn)
RedisConfig配置
新建RedisConfig配置類
package com.bdqn.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.time.Duration;
/**
* @author cuishujian
* @date 2024/9/25
*/
@Configuration
@EnableCaching// 開啟緩存
public class RedisConfig extends CachingConfigurerSupport {
/**
* 自定義生成 key的規(guī)則
* 緩存對象集合中,緩存是以 key-value 形式保存的
* 當(dāng)不指定緩存的 key時,SpringBoot會使用 SimpleKeyGenerator 生成 key
* @return
*/
@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
public Object generate(Object target, Method method, Object... params){
// 格式化緩存key字符串
StringBuilder sb = new StringBuilder();
// 追加類名
sb.append(target.getClass().getName());
// 追加方法名
sb.append(method.getName());
// 遍歷參數(shù)并且追加
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 解決查詢緩存轉(zhuǎn)換異常的問題
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// 使用Jackson2JsonRedisSerialize 替換默認(rèn)序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(om, Object.class);
// 設(shè)置value的序列化對象和key的序列化對象
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 采用RedisCacheManager作為緩存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
// 創(chuàng)建Redis序列化對象
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
// 解決查詢緩存轉(zhuǎn)換異常的問題
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// 創(chuàng)建Jackson的序列化對象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(om, Object.class);
// 配置序列化(解決亂碼問題)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
// 7天緩存過期
.entryTtl(Duration.ofDays(7))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}以上代碼說明如下:
@EnableCaching:使用此注解開啟緩存
keyGenerator():使用此方法自定義key生成規(guī)則
redisTemplate():使用此方法改變默認(rèn)的序列化規(guī)則,將數(shù)據(jù)序列化為json格式。當(dāng)我們引入了spring-boot-starter-data-reids時,RedisAutoConfiguration自動配置類幫我們注入了RedisTemplate<Object,Object>和StringRedisTemplate兩個組件來操作redis,其中RedisTemplate<Object,Object>的鍵值都是對象,StringRedisTemplate用來操作字符串的。RedisTemplate使用的是JdkSerializationRedisSerializer,存入數(shù)據(jù)會將數(shù)據(jù)先序列化成字節(jié)數(shù)據(jù)然后再存入Redis,如果希望將數(shù)據(jù)序列化為json格式,則要改變默認(rèn)的序列化規(guī)則
cacheManager():使用此方法自定義RedisCacheManager改變默認(rèn)的序列化規(guī)則,將數(shù)據(jù)序列化為json格式
Cache注解
@Cacheable
- 作用:主要針對方法配置,能夠根據(jù)方法的請求參數(shù)對其結(jié)果進(jìn)行緩存。在查詢時,會先從緩存中取數(shù)據(jù),若不存在才再發(fā)起對數(shù)據(jù)庫的訪問。
- 參數(shù):
value/cacheNames:指定緩存存儲的集合名。key:緩存對象存儲在Map集合中的key值,非必需,缺省按照函數(shù)的所有參數(shù)組合作為key值,若自己配置需使用SpEL表達(dá)式。condition:緩存對象的條件,非必需,也需使用SpEL表達(dá)式,只有滿足表達(dá)式條件的內(nèi)容才會被緩存。unless:另一個緩存條件參數(shù),非必需,也需使用SpEL表達(dá)式,但判斷時機在函數(shù)被調(diào)用之后,所以它可以通過對result進(jìn)行判斷。keyGenerator:用于指定key生成器,非必需。cacheManager:用于指定使用哪個緩存管理器,非必需。cacheResolver:用于指定使用哪個緩存解析器,非必需。
- 示例:
@Cacheable(value = "user", key = "#id"),表示使用id作為key,將方法的返回結(jié)果緩存到名為“user”的緩存中。
@CachePut
- 作用:主要針對方法配置,能夠根據(jù)方法的請求參數(shù)對其結(jié)果進(jìn)行緩存,并且每次都會觸發(fā)真實方法的調(diào)用(與@Cacheable不同)。主要用于數(shù)據(jù)新增和修改操作上。
- 參數(shù):與@Cacheable類似。
- 示例:
@CachePut(value = "user", key = "#user.id"),表示以user.id作為key,將方法的返回結(jié)果更新到名為“user”的緩存中。
@CacheEvict
- 作用:主要針對方法配置,能夠根據(jù)一定的條件對緩存進(jìn)行清空。通常用在刪除方法上。
- 參數(shù):
value/cacheNames:指定緩存存儲的集合名。key:指定清除數(shù)據(jù)的key值。allEntries:非必需,默認(rèn)為false。若設(shè)置為true,則清除緩存組件下的所有數(shù)據(jù)。beforeInvocation:非必需,默認(rèn)為false。若設(shè)置為true,則在方法執(zhí)行前清除緩存,否則在方法執(zhí)行后清除。
- 示例:
@CacheEvict(value = "user", key = "#id"),表示從名為“user”的緩存中移除key為id的數(shù)
到此這篇關(guān)于SpringBoot集成Redis使用Cache緩存的文章就介紹到這了,更多相關(guān)SpringBoot使用Cache緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中@PathVariable、@RequestParam和@RequestBody的區(qū)別和使用詳解
這篇文章主要介紹了SpringBoot中@PathVariable、@RequestParam和@RequestBody的區(qū)別和使用詳解,@PathVariable 映射 URL 綁定的占位符,通過@RequestMapping注解中的{}占位符來標(biāo)識URL中的變量部分,需要的朋友可以參考下2024-01-01

