Spring?Boot整合?NoSQL?數(shù)據(jù)庫?Redis詳解
引言
在日常的開發(fā)中,除了使用 Spring Boot 這個企業(yè)級快速構建項目的框架之外,隨著業(yè)務數(shù)據(jù)量的大幅度增加,對元數(shù)據(jù)庫造成的壓力成倍劇增。在此背景下, Redis 這個 NoSQL 數(shù)據(jù)庫已然整個項目架構中的不可或缺的一部分,懂得如何 Spring Boot 整合 Redis ,是當今開發(fā)人員必備的一項技能,接下來對整合步驟進行詳細說明。
一、環(huán)境準備
在開始開發(fā)之前,我們需要準備一些環(huán)境配置:
- jdk 1.8 或其他更高版本
- 開發(fā)工具 IDEA
- 管理依賴 Maven
- Redis環(huán)境,推薦linux系統(tǒng)中搭建redis環(huán)境
二、構建Spring Boot項目
打開 idea -> file -> Nwe -> Project ,如圖,勾選填寫相關的配置信息:

勾選一些初始化的依賴配置:

Spring Boot項目初始化完成。

三、引入Redis依賴
構建完成Spring Boot項目工程之后,需要在 pom.xml 文件中引入 redis 相關依賴
<!-- 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相關配置
將redis相關的依賴引入到項目中之后,需要對redis進行一些配置,在 application.properties配置redis:
# Redis服務器地址 spring.redis.host=自己搭建的redis服務器的 IP # Redis服務器連接端口 spring.redis.port=6379 # Redis數(shù)據(jù)庫索引(默認為0) spring.redis.database= 0 # 連接超時時間(毫秒) spring.redis.timeout=1800000 # 連接池最大連接數(shù)(使用負值表示沒有限制) spring.redis.lettuce.pool.max-active=20 # 最大阻塞等待時間(負數(shù)表示沒限制) spring.redis.lettuce.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.lettuce.pool.max-idle=5 # 連接池中的最小空閑連接 spring.redis.lettuce.pool.min-idle=0

五、添加Redis配置類
對Redis相關配置完成后,添加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)境依賴和配置搭建完成之后,進行測試一把。
① 首先,確保安裝 Redis 的服務器已經(jīng)啟動Redis服務

② 編寫 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(){
// 設置值到reids
redisTemplate.opsForValue().set("name","jack");
// 從redis中獲取值
String name = (String)redisTemplate.opsForValue().get("name");
return name;
}
}
③ 啟動Spring Boot工程,在瀏覽器上向接口發(fā)送請求:

項目啟動成功,向 /redistest 接口發(fā)送請求

請求發(fā)送成功,獲取到數(shù)據(jù),測試成功,至此Spring Boot整合 Redis所有步驟已經(jīng)完成,更多關于SpringBoot整合NoSQL Redis的資料請關注腳本之家其它相關文章!
相關文章
Spring?Cloud?使用?Resilience4j?實現(xiàn)服務熔斷的方法
服務熔斷是為了保護我們的服務,比如當某個服務出現(xiàn)問題的時候,控制打向它的流量,讓它有時間去恢復,或者限制一段時間只能有固定數(shù)量的請求打向這個服務,這篇文章主要介紹了Spring?Cloud?使用?Resilience4j?實現(xiàn)服務熔斷,需要的朋友可以參考下2022-12-12
Spring注解Autowired的底層實現(xiàn)原理詳解
從當前springboot的火熱程度來看,java?config的應用是越來越廣泛了,在使用java?config的過程當中,我們不可避免的會有各種各樣的注解打交道,其中,我們使用最多的注解應該就是@Autowired注解了。本文就來聊聊Autowired的底層實現(xiàn)原理2022-10-10
Zookeeper中如何解決zookeeper.out文件輸出位置問題
這篇文章主要介紹了Zookeeper中如何解決zookeeper.out文件輸出位置問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

