SpringBoot集成Redis使用Cache緩存的實(shí)現(xiàn)方法
使用SpringBoot集成Redis使用Cache緩存只要配置相應(yīng)的配置類,然后使用Cache注解就能實(shí)現(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ī)則 * 緩存對(duì)象集合中,緩存是以 key-value 形式保存的 * 當(dāng)不指定緩存的 key時(shí),SpringBoot會(huì)使用 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的序列化對(duì)象和key的序列化對(duì)象 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 采用RedisCacheManager作為緩存管理器 */ @Bean public CacheManager cacheManager(RedisConnectionFactory factory){ // 創(chuàng)建Redis序列化對(duì)象 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的序列化對(duì)象 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時(shí),RedisAutoConfiguration自動(dòng)配置類幫我們注入了RedisTemplate<Object,Object>和StringRedisTemplate兩個(gè)組件來操作redis,其中RedisTemplate<Object,Object>的鍵值都是對(duì)象,StringRedisTemplate用來操作字符串的。RedisTemplate使用的是JdkSerializationRedisSerializer,存入數(shù)據(jù)會(huì)將數(shù)據(jù)先序列化成字節(jié)數(shù)據(jù)然后再存入Redis,如果希望將數(shù)據(jù)序列化為json格式,則要改變默認(rèn)的序列化規(guī)則
cacheManager():使用此方法自定義RedisCacheManager改變默認(rèn)的序列化規(guī)則,將數(shù)據(jù)序列化為json格式
Cache注解
@Cacheable
- 作用:主要針對(duì)方法配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存。在查詢時(shí),會(huì)先從緩存中取數(shù)據(jù),若不存在才再發(fā)起對(duì)數(shù)據(jù)庫的訪問。
- 參數(shù):
value
/cacheNames
:指定緩存存儲(chǔ)的集合名。key
:緩存對(duì)象存儲(chǔ)在Map集合中的key值,非必需,缺省按照函數(shù)的所有參數(shù)組合作為key值,若自己配置需使用SpEL表達(dá)式。condition
:緩存對(duì)象的條件,非必需,也需使用SpEL表達(dá)式,只有滿足表達(dá)式條件的內(nèi)容才會(huì)被緩存。unless
:另一個(gè)緩存條件參數(shù),非必需,也需使用SpEL表達(dá)式,但判斷時(shí)機(jī)在函數(shù)被調(diào)用之后,所以它可以通過對(duì)result進(jìn)行判斷。keyGenerator
:用于指定key生成器,非必需。cacheManager
:用于指定使用哪個(gè)緩存管理器,非必需。cacheResolver
:用于指定使用哪個(gè)緩存解析器,非必需。
- 示例:
@Cacheable(value = "user", key = "#id")
,表示使用id作為key,將方法的返回結(jié)果緩存到名為“user”的緩存中。
@CachePut
- 作用:主要針對(duì)方法配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存,并且每次都會(huì)觸發(fā)真實(shí)方法的調(diào)用(與@Cacheable不同)。主要用于數(shù)據(jù)新增和修改操作上。
- 參數(shù):與@Cacheable類似。
- 示例:
@CachePut(value = "user", key = "#user.id")
,表示以u(píng)ser.id作為key,將方法的返回結(jié)果更新到名為“user”的緩存中。
@CacheEvict
- 作用:主要針對(duì)方法配置,能夠根據(jù)一定的條件對(duì)緩存進(jìn)行清空。通常用在刪除方法上。
- 參數(shù):
value
/cacheNames
:指定緩存存儲(chǔ)的集合名。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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用IDEA搭建一個(gè)簡(jiǎn)單的SpringBoot項(xiàng)目超詳細(xì)過程
這篇文章主要介紹了使用IDEA搭建一個(gè)簡(jiǎn)單的SpringBoot項(xiàng)目超詳細(xì)過程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02springboot如何讀取application.yml文件
這篇文章主要介紹了springboot如何讀取application.yml文件的方法,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-12-12舉例講解Java設(shè)計(jì)模式編程中Decorator裝飾者模式的運(yùn)用
這篇文章主要介紹了Java設(shè)計(jì)模式編程中Decorator裝飾者模式的運(yùn)用,裝飾者模式就是給一個(gè)對(duì)象動(dòng)態(tài)的添加新的功能,裝飾者和被裝飾者實(shí)現(xiàn)同一個(gè)接口,裝飾者持有被裝飾者的實(shí)例,需要的朋友可以參考下2016-05-05java中設(shè)計(jì)模式(多例)的實(shí)例詳解
這篇文章主要介紹了java中設(shè)計(jì)模式(多例)的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09輕松學(xué)會(huì)使用JavaMail?API發(fā)送郵件
想要輕松學(xué)會(huì)使用JavaMail?API發(fā)送郵件嗎?本指南將帶你快速掌握這一技能,讓你能夠輕松發(fā)送電子郵件,無論是個(gè)人還是工作需求,跟著我們的步驟,很快你就可以在Java應(yīng)用程序中自如地處理郵件通信了!2023-12-12java設(shè)計(jì)模式原型模式與享元模式調(diào)優(yōu)系統(tǒng)性能詳解
這篇文章主要為大家介紹了java設(shè)計(jì)模式原型模式與享元模式調(diào)優(yōu)系統(tǒng)性能方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05java selenium Selenium IDE介紹及用法
本文主要介紹java selenium Selenium IDE,這里整理了相關(guān)資料和介紹如何安裝 Selenium IDE和使用方法,有需要的小伙伴可以參考下2016-08-08SWT(JFace)體驗(yàn)之圓環(huán)狀(戒指型)
SWT(JFace)體驗(yàn)之圓環(huán)狀(戒指型)實(shí)現(xiàn)代碼。2009-06-06