Spring?Boot?整合?Redis?實現(xiàn)數(shù)據(jù)緩存案例詳解
Spring Boot 緩存,默認(rèn)使用的是 ConcurrentMap 的方式來實現(xiàn)的,然而我們在項目中并不會這么使用。我們經(jīng)常會引入第三方緩存框架,來完成對數(shù)據(jù)的緩存操作。比如說:Redis 。本文就來介紹 Spring Boot 整合 Redis 來實現(xiàn)數(shù)據(jù)的緩存。
1.添加 Maven 依賴
<!--引入 redis starter 的maven依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.配置redis屬性
spring.redis.host=192.168.204.211 spring.redis.port=6379 spring.redis.password=xxx spring.redis.database=0 # 設(shè)置連接池配置等(如有需要) spring.redis.lettuce.pool.max-active=xxx spring.redis.lettuce.pool.max-idle=xxx
配置好 redis 相關(guān)屬性之后,Spring Boot 在項目啟動時,便會自動為我們注入 redisTemplate、stringRedisTemplate 組件。
因為我們操作緩存大多數(shù)都是對字符串進行操作。所以為我們專門抽取出來的一個 stringRedisTemplate 組件,方便我們的使用。
3.創(chuàng)建 redisCacheManager
引入 redis 來實現(xiàn)緩存,此時我們便使用 RedisCacheManager 來進行管理了。我們在使用 RedisCacheManager 來操作 redis 時,底層操作默認(rèn)使用的是 RedisTemplate,而 redisTemplate 是 redisAutoConfiguration 在項目啟動時幫我們自動注冊的組件,它默認(rèn)使用的是 JDK 序列化機制。所以在 redis 存儲時,會出現(xiàn)類似亂碼的情況出現(xiàn)。所以我們需要來自己配置 redisCacheManager。
新建一個配置類 MyRedisConfig.java
,使用@Configuration 注解來標(biāo)注該類是一個配置類。然后使用 @Bean 注解為 IOC 容器注冊我們自定義的 redisCacheManager,代碼如下所示:
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; 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.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.time.Duration; /** * 自定義 Redis緩存相關(guān)配置 */ @EnableCaching @Configuration public class MyRedisConfig { /** * 自定義CacheManager管理器 * @param redisConnectionFactory * @return */ @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){ RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);//這一句必須要,作用是序列化時將對象全類名一起保存下來 om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //配置序列化(解決亂碼的問題) RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(300))//設(shè)置 key 過期時間 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) //設(shè)置key序列化規(guī)則 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))//設(shè)置value序列化規(guī)則 .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config) .build(); return cacheManager; } }
4.使用Spring提供的注解,實現(xiàn)緩存數(shù)據(jù)到 Redis
使用 @Cacheable
、@CachePut
、@CacheEvict
等注解來實現(xiàn)緩存功能,此處不再過多介紹,可參考:Spring 緩存在項目中的使用。測試圖如下所示:
5.完成對操作過程中數(shù)據(jù)的緩存
使用 @Cacheable 等注解,都是將最終的結(jié)果進行緩存。如果我們需要對過程中的部分?jǐn)?shù)據(jù)也進行緩存,我們此時就需要使用 RedisCacheManager
來手動操作。
/** * 如果有多個cacheManager,也可以來手動指定使用哪個 */ @Override @Cacheable(value = "user", key = "#root.methodName +'['+ #id +']'",cacheManager = "redisCacheManager") public User getUser(Integer id) { log.info("用戶"+id+"開始執(zhí)行數(shù)據(jù)庫查詢"); User user = userMapper.getUser(id); return user; }
也可以直接使用CacheManager來對中間結(jié)果緩存
@Override public User getUser(Integer id) { log.info("用戶"+id+"開始執(zhí)行數(shù)據(jù)庫查詢"); User user = userMapper.getUser(id); //可以直接使用CacheManager來對中間結(jié)果緩存 Cache cache = cacheManager.getCache("user"); cache.put("test",1111); return user; }
6.附 demo 實例
Spring Boot 整合 Redis 實現(xiàn)數(shù)據(jù)緩存
百度網(wǎng)盤下載地址:
鏈接: https://pan.baidu.com/s/16bNmeIynFTHJ88PGf5ux4A
提取碼: jm67
到此這篇關(guān)于Spring Boot 整合 Redis 實現(xiàn)數(shù)據(jù)緩存的文章就介紹到這了,更多相關(guān)Spring Boot Redis 數(shù)據(jù)緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用dynamic datasource springboot starter實現(xiàn)多數(shù)據(jù)源及源碼分析
這篇文章主要介紹了使用dynamic-datasource-spring-boot-starter做多數(shù)據(jù)源及源碼分析,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實現(xiàn)
本文主要介紹了IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07基于SpringBoot應(yīng)用監(jiān)控Actuator安全隱患及解決方式
這篇文章主要介紹了SpringBoot應(yīng)用監(jiān)控Actuator安全隱患及解決方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07JSON數(shù)據(jù)轉(zhuǎn)換成Java對象的方法
就目前來講,將Java對象轉(zhuǎn)換成JSON對象還是相當(dāng)簡單的,但是 將JSON對象轉(zhuǎn)換成Java對象,就相對比較復(fù)雜了些2014-03-03