Spring?Boot整合?NoSQL?數(shù)據(jù)庫(kù)?Redis詳解
引言
在日常的開(kāi)發(fā)中,除了使用 Spring Boot
這個(gè)企業(yè)級(jí)快速構(gòu)建項(xiàng)目的框架之外,隨著業(yè)務(wù)數(shù)據(jù)量的大幅度增加,對(duì)元數(shù)據(jù)庫(kù)造成的壓力成倍劇增。在此背景下, Redis
這個(gè) NoSQL
數(shù)據(jù)庫(kù)已然整個(gè)項(xiàng)目架構(gòu)中的不可或缺的一部分,懂得如何 Spring Boot
整合 Redis
,是當(dāng)今開(kāi)發(fā)人員必備的一項(xiàng)技能,接下來(lái)對(duì)整合步驟進(jìn)行詳細(xì)說(shuō)明。
一、環(huán)境準(zhǔn)備
在開(kāi)始開(kāi)發(fā)之前,我們需要準(zhǔn)備一些環(huán)境配置:
- jdk 1.8 或其他更高版本
- 開(kāi)發(fā)工具 IDEA
- 管理依賴(lài) Maven
- Redis環(huán)境,推薦linux系統(tǒng)中搭建redis環(huán)境
二、構(gòu)建Spring Boot項(xiàng)目
打開(kāi) idea -> file -> Nwe -> Project
,如圖,勾選填寫(xiě)相關(guān)的配置信息:
勾選一些初始化的依賴(lài)配置:
Spring Boot項(xiàng)目初始化完成。
三、引入Redis依賴(lài)
構(gòu)建完成Spring Boot項(xiàng)目工程之后,需要在 pom.xml
文件中引入 redis
相關(guān)依賴(lài)
<!-- 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)的依賴(lài)引入到項(xiàng)目中之后,需要對(duì)redis進(jìn)行一些配置,在 application.properties
配置redis:
# Redis服務(wù)器地址 spring.redis.host=自己搭建的redis服務(wù)器的 IP # Redis服務(wù)器連接端口 spring.redis.port=6379 # Redis數(shù)據(jù)庫(kù)索引(默認(rèn)為0) spring.redis.database= 0 # 連接超時(shí)時(shí)間(毫秒) spring.redis.timeout=1800000 # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制) spring.redis.lettuce.pool.max-active=20 # 最大阻塞等待時(shí)間(負(fù)數(shù)表示沒(méi)限制) spring.redis.lettuce.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.lettuce.pool.max-idle=5 # 連接池中的最小空閑連接 spring.redis.lettuce.pool.min-idle=0
五、添加Redis配置類(lèi)
對(duì)Redis相關(guān)配置完成后,添加Redis配置類(lèi),(拿來(lái)即用):
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)換異常的問(wèn)題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問(wèn)題),過(guò)期時(shí)間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; } }
六、測(cè)試一下
將所有的環(huán)境依賴(lài)和配置搭建完成之后,進(jìn)行測(cè)試一把。
① 首先,確保安裝 Redis
的服務(wù)器已經(jīng)啟動(dòng)Redis服務(wù)
② 編寫(xiě) controller
類(lèi),前提需要引入 Spring Boot Web
的依賴(lài):
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; } }
③ 啟動(dòng)Spring Boot工程,在瀏覽器上向接口發(fā)送請(qǐng)求:
項(xiàng)目啟動(dòng)成功,向 /redistest
接口發(fā)送請(qǐng)求
請(qǐng)求發(fā)送成功,獲取到數(shù)據(jù),測(cè)試成功,至此Spring Boot整合 Redis所有步驟已經(jīng)完成,更多關(guān)于SpringBoot整合NoSQL Redis的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring?Cloud?使用?Resilience4j?實(shí)現(xiàn)服務(wù)熔斷的方法
服務(wù)熔斷是為了保護(hù)我們的服務(wù),比如當(dāng)某個(gè)服務(wù)出現(xiàn)問(wèn)題的時(shí)候,控制打向它的流量,讓它有時(shí)間去恢復(fù),或者限制一段時(shí)間只能有固定數(shù)量的請(qǐng)求打向這個(gè)服務(wù),這篇文章主要介紹了Spring?Cloud?使用?Resilience4j?實(shí)現(xiàn)服務(wù)熔斷,需要的朋友可以參考下2022-12-12Java中volatile關(guān)鍵字的作用與用法詳解
volatile關(guān)鍵字雖然從字面上理解起來(lái)比較簡(jiǎn)單,但是要用好不是一件容易的事情。這篇文章主要介紹了Java中volatile關(guān)鍵字的作用與用法詳解的相關(guān)資料,需要的朋友可以參考下2016-09-09Spring注解Autowired的底層實(shí)現(xiàn)原理詳解
從當(dāng)前springboot的火熱程度來(lái)看,java?config的應(yīng)用是越來(lái)越廣泛了,在使用java?config的過(guò)程當(dāng)中,我們不可避免的會(huì)有各種各樣的注解打交道,其中,我們使用最多的注解應(yīng)該就是@Autowired注解了。本文就來(lái)聊聊Autowired的底層實(shí)現(xiàn)原理2022-10-10Zookeeper中如何解決zookeeper.out文件輸出位置問(wèn)題
這篇文章主要介紹了Zookeeper中如何解決zookeeper.out文件輸出位置問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04