Spring?Boot整合?NoSQL?數(shù)據(jù)庫?Redis詳解
引言
在日常的開發(fā)中,除了使用 Spring Boot
這個企業(yè)級快速構(gòu)建項(xiàng)目的框架之外,隨著業(yè)務(wù)數(shù)據(jù)量的大幅度增加,對元數(shù)據(jù)庫造成的壓力成倍劇增。在此背景下, Redis
這個 NoSQL
數(shù)據(jù)庫已然整個項(xiàng)目架構(gòu)中的不可或缺的一部分,懂得如何 Spring Boot
整合 Redis
,是當(dāng)今開發(fā)人員必備的一項(xiàng)技能,接下來對整合步驟進(jìn)行詳細(xì)說明。
一、環(huán)境準(zhǔn)備
在開始開發(fā)之前,我們需要準(zhǔn)備一些環(huán)境配置:
- jdk 1.8 或其他更高版本
- 開發(fā)工具 IDEA
- 管理依賴 Maven
- Redis環(huán)境,推薦linux系統(tǒng)中搭建redis環(huán)境
二、構(gòu)建Spring Boot項(xiàng)目
打開 idea -> file -> Nwe -> Project
,如圖,勾選填寫相關(guān)的配置信息:
勾選一些初始化的依賴配置:
Spring Boot項(xiàng)目初始化完成。
三、引入Redis依賴
構(gòu)建完成Spring Boot項(xiàng)目工程之后,需要在 pom.xml
文件中引入 redis
相關(guān)依賴
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring2.X集成redis所需common-pool2--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency>
四、Reds相關(guān)配置
將redis相關(guān)的依賴引入到項(xiàng)目中之后,需要對redis進(jìn)行一些配置,在 application.properties
配置redis:
# Redis服務(wù)器地址 spring.redis.host=自己搭建的redis服務(wù)器的 IP # Redis服務(wù)器連接端口 spring.redis.port=6379 # Redis數(shù)據(jù)庫索引(默認(rèn)為0) spring.redis.database= 0 # 連接超時時間(毫秒) spring.redis.timeout=1800000 # 連接池最大連接數(shù)(使用負(fù)值表示沒有限制) spring.redis.lettuce.pool.max-active=20 # 最大阻塞等待時間(負(fù)數(shù)表示沒限制) spring.redis.lettuce.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.lettuce.pool.max-idle=5 # 連接池中的最小空閑連接 spring.redis.lettuce.pool.min-idle=0
五、添加Redis配置類
對Redis相關(guān)配置完成后,添加Redis配置類,(拿來即用):
package com.zhao.demo.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.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.time.Duration; /** * @author xiaoZhao * @date 2022/9/6 * @describe */ @EnableCaching @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { 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.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問題),過期時間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
六、測試一下
將所有的環(huán)境依賴和配置搭建完成之后,進(jìn)行測試一把。
① 首先,確保安裝 Redis
的服務(wù)器已經(jīng)啟動Redis服務(wù)
② 編寫 controller
類,前提需要引入 Spring Boot Web
的依賴:
package com.zhao.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author xiaoZhao * @date 2022/9/6 * @describe */ @RestController @RequestMapping("/redistest") public class RedisTestController { @Autowired private RedisTemplate redisTemplate; @GetMapping public String testRedis(){ // 設(shè)置值到reids redisTemplate.opsForValue().set("name","jack"); // 從redis中獲取值 String name = (String)redisTemplate.opsForValue().get("name"); return name; } }
③ 啟動Spring Boot工程,在瀏覽器上向接口發(fā)送請求:
項(xiàng)目啟動成功,向 /redistest
接口發(fā)送請求
請求發(fā)送成功,獲取到數(shù)據(jù),測試成功,至此Spring Boot整合 Redis所有步驟已經(jīng)完成,更多關(guān)于SpringBoot整合NoSQL Redis的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring?Cloud?使用?Resilience4j?實(shí)現(xiàn)服務(wù)熔斷的方法
服務(wù)熔斷是為了保護(hù)我們的服務(wù),比如當(dāng)某個服務(wù)出現(xiàn)問題的時候,控制打向它的流量,讓它有時間去恢復(fù),或者限制一段時間只能有固定數(shù)量的請求打向這個服務(wù),這篇文章主要介紹了Spring?Cloud?使用?Resilience4j?實(shí)現(xiàn)服務(wù)熔斷,需要的朋友可以參考下2022-12-12Java中volatile關(guān)鍵字的作用與用法詳解
volatile關(guān)鍵字雖然從字面上理解起來比較簡單,但是要用好不是一件容易的事情。這篇文章主要介紹了Java中volatile關(guān)鍵字的作用與用法詳解的相關(guān)資料,需要的朋友可以參考下2016-09-09Spring注解Autowired的底層實(shí)現(xiàn)原理詳解
從當(dāng)前springboot的火熱程度來看,java?config的應(yīng)用是越來越廣泛了,在使用java?config的過程當(dāng)中,我們不可避免的會有各種各樣的注解打交道,其中,我們使用最多的注解應(yīng)該就是@Autowired注解了。本文就來聊聊Autowired的底層實(shí)現(xiàn)原理2022-10-10Zookeeper中如何解決zookeeper.out文件輸出位置問題
這篇文章主要介紹了Zookeeper中如何解決zookeeper.out文件輸出位置問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04