Spring?Boot2?整合連接?Redis的操作方法
1.在 springboot 中 , 整合 redis
可以通過 RedisTemplate 完成對 redis 的操作, 包括設(shè)置數(shù)據(jù)/獲取數(shù)據(jù)
比如添加和讀取數(shù)據(jù)
具體整合實現(xiàn):
創(chuàng)建 Maven 項目:



在 pom.xml 文件當(dāng)中導(dǎo)入相關(guān)的 jar 依賴。如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rainbowsea</groupId>
<artifactId>redis_springboot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<!-- 說明: 如果這里是 spring-boot-start 就改成如下 spring-boot-start-web-->
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X 集成 redis 所需 common-pool-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<!--不要帶版本號,防止沖突-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- json 轉(zhuǎn)換的 jar 包依賴-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
</dependencies>
<!-- 插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>在 resources 目錄下創(chuàng)建 application.properties,完成 redis 的基本配置,如下所示:

#Redis 服務(wù)器地址 spring.redis.host=192.168.76.145 #Redis 服務(wù)器連接端口 spring.redis.port=6379 #Redis 如果有密碼,需要配置, 沒有密碼就不要寫 spring.redis.password=rainbowsea #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
創(chuàng)建/定義一個 Redis 配置類。
- 這個 Redis 配置類是對要使用 RedisTemplate bean 對象的配置,可以理解成是一個常規(guī)配置。
- 和我們以前學(xué)過的一個 JdbcTemplate 的設(shè)計理念類似。
- 如果不是配置,那么 Spring boot 會使用默認(rèn)配置,這個默認(rèn)配置,會出現(xiàn)一些問題,比如:redisTemplate 的 key 序列化等問題,所以通常我們需要配置這個。Redis 配置類.
創(chuàng)建:\redis_springboot\src\main\java\com\rainbowsea\redis\config\ RedisConfig.java 配置類

package com.rainbowsea.redis.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
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;
@EnableCaching // 配置開啟緩存
@Configuration // 定義配置類
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template =
new RedisTemplate<>();
System.out.println("template=>" + template);
RedisSerializer<String> redisSerializer =
new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
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.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
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;
}
}創(chuàng)建 controller 訪問設(shè)置/獲取到 Redis 數(shù)據(jù)庫當(dāng)中的數(shù)據(jù)。

重點: 我們這里的
RedisTemplate模板對象,就是已經(jīng)配置好了 Jedis 的連接上 Redis的一個模板,該模板提供了很多,我們操作 Redis 數(shù)據(jù)庫的方法。就和我們前面學(xué)習(xí) MySQL ,操作連接 MySQL 當(dāng)中的 JdbcTemplate 模板是類似的。
如下所示:

package com.rainbowsea.redis.controller;
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;
import javax.annotation.Resource;
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
// 裝配 RedisTemplate
@Resource
private RedisTemplate redisTemplate;
// 編寫一個測試方法
// 演示設(shè)置數(shù)據(jù)和獲取數(shù)據(jù)
@GetMapping("/t1")
public String t1() {
// 設(shè)置值到 redis 當(dāng)中,opsForValue 是操作 string 字符串的
redisTemplate.opsForValue().set("book", "天龍八部");
// 從 redis 當(dāng)中獲取值
String book = (String) redisTemplate.opsForValue().get("book");
return book;
}
}創(chuàng)建場景啟動器。


package com.rainbowsea.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(RedisSpringBootApplication.class, args);
}
}啟動程序run, 打開瀏覽器地址欄上輸入:http://localhost:9090/redisTest/t1 。
**演示:如何操作 List **


package com.rainbowsea.redis.controller;
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;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
// 裝配 RedisTemplate
@Resource
private RedisTemplate redisTemplate;
// 演示如何操作 list 列表
@GetMapping("/t2")
public String t2() {
// list-存
redisTemplate.opsForList().leftPush("books", "笑傲江湖");
redisTemplate.opsForList().leftPush("books", "hello world");
// list - 取數(shù)據(jù)
List books = redisTemplate.opsForList().range("books", 0, -1);
String booksList = "";
for (Object book : books) {
System.out.println("book->" + book.toString());
booksList += book.toString();
}
return booksList;
}
// 編寫一個測試方法
// 演示設(shè)置數(shù)據(jù)和獲取數(shù)據(jù)
@GetMapping("/t1")
public String t1() {
// 設(shè)置值到 redis 當(dāng)中,opsForValue 是操作 string 字符串的
redisTemplate.opsForValue().set("book", "天龍八部");
// 從 redis 當(dāng)中獲取值
String book = (String) redisTemplate.opsForValue().get("book");
return book;
}
}
演示:如何操作 hash


@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
// 裝配 RedisTemplate
@Resource
private RedisTemplate redisTemplate;
@GetMapping("/t3")
public String t3() {
// hash - 存數(shù)據(jù)
redisTemplate.opsForHash();
// 操作 Zset 有序集合
redisTemplate.opsForZSet();
// 操作 set 集合
redisTemplate.opsForSet();
return null;
}2. 注意事項和細(xì)節(jié)
如果沒有提供 RedisConfig 配置類 , springboot 會使用默認(rèn)配置 也可以使用。但是會存在問題。比如 redisTemplate 模糊查找 key 數(shù)據(jù)為空。
測試:
這里我們先將 我們配置的 RedisConfig 配置類注釋掉。

編寫一個方法,獲取所有的 key:
*,表示獲取所有的 key

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
// 裝配 RedisTemplate
@Resource
private RedisTemplate redisTemplate;
// 編寫一個方法,獲取所有的 key
@GetMapping("/t3")
public String t3() {
Set keys = redisTemplate.keys("*");
for (Object key : keys) {
System.out.println("key -->" + key.toString());
}
return "OK";
}
}
**當(dāng)我們將我們的配置的 RedisConfig 類打開,不使用 Spring Boot 默認(rèn)的配置。則不會出現(xiàn)該空的情況。 **


Unrecognized token 'beijing': was expecting ('true', 'false' or 'null')
看報錯,是 jason 轉(zhuǎn)換異常,實際上是因為 redisTemplate 在做數(shù)據(jù)存儲的時候會把存儲的內(nèi)容序列化,所以,redisTemplate 讀取的時候也會反序列化,而在 redis 客戶端 set 的時候并不會做序列化,因此 set 的進去的值在用 redisTemplate 讀的時候就會報類 型轉(zhuǎn)換異常了。
演示:
我們在 Redis 命令行客戶端(不通過Java程序的方式),創(chuàng)建 一個 k100的字符串。
然后,我們再通過Java程序獲取到該(Redis命令行客戶端)所創(chuàng)建的 k100 字符串的數(shù)據(jù)。



解決這個
com.fasterxml.jackson.core.JsonParseException也簡單,既然我們 Resi 命令行客戶端(創(chuàng)建的 對象信息/值)不會被序列化,那我們就不用 Redis 命令行客戶端創(chuàng)建對象了,直接就是。我們想用Java程序當(dāng)中反序化的功能:我們就用 Java程序創(chuàng)建對象/值,同時也用Java程序獲取對象的數(shù)據(jù)。存和取都保持一致,都是在Java程序當(dāng)中即可(因為Java程序創(chuàng)建的對象會自行序列化的)。這里就不演示了,因為我們上述的所有操作都是:Java程序連接 Redis 創(chuàng)建對象,也是Java程序獲取數(shù)據(jù)。都是沒問題的。
3. 最后:
“在這個最后的篇章中,我要表達(dá)我對每一位讀者的感激之情。你們的關(guān)注和回復(fù)是我創(chuàng)作的動力源泉,我從你們身上吸取了無盡的靈感與勇氣。我會將你們的鼓勵留在心底,繼續(xù)在其他的領(lǐng)域奮斗。感謝你們,我們總會在某個時刻再次相遇。”
到此這篇關(guān)于 Spring Boot2 整合連接 Redis的操作方法的文章就介紹到這了,更多相關(guān)Spring Boot2 連接 Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot實現(xiàn)自定義Redis的連接的流程步驟
- SpringBoot無法連接redis的解決方案
- springBoot連接遠(yuǎn)程Redis連接失敗的問題解決
- 關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例
- springboot連接不上redis的三種解決辦法
- springboot連接redis并動態(tài)切換database的實現(xiàn)方法
- springboot 如何使用jedis連接Redis數(shù)據(jù)庫
- springboot連接Redis的教程詳解
- springboot2整合redis使用lettuce連接池的方法(解決lettuce連接池?zé)o效問題)
- 基于SpringBoot2.0默認(rèn)使用Redis連接池的配置操作
- Springboot2.X集成redis集群(Lettuce)連接的方法
相關(guān)文章
Java 中String StringBuilder 與 StringBuffer詳解及用法實例
這篇文章主要介紹了Java 中String StringBuilder 與 StringBuffer詳解及用法實例的相關(guān)資料,需要的朋友可以參考下2017-02-02
微服務(wù)springcloud 03.Eureka實現(xiàn)高可用的過程
這篇文章主要介紹了微服務(wù)springcloud 03.Eureka實現(xiàn)高可用的相關(guān)資料,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07
SSH框架網(wǎng)上商城項目第24戰(zhàn)之Struts2中處理多個Model請求的方法
這篇文章主要為大家詳細(xì)介紹了SSH框架網(wǎng)上商城項目第24戰(zhàn)之Struts2中處理多個Model請求的方法,感興趣的小伙伴們可以參考一下2016-06-06
Java如何接收XML格式參數(shù)并轉(zhuǎn)換為JSON
在 Java 應(yīng)用程序中,處理 XML 數(shù)據(jù)并將其轉(zhuǎn)換為 JSON 格式是很常見的任務(wù),這篇文章為大家整理了一下具體的實現(xiàn)方法,希望對大家有所幫助2025-03-03

