SpringBoot整合Redis實(shí)現(xiàn)序列化存儲Java對象的操作方法
之前介紹過 http://www.dbjr.com.cn/article/223539.htm 我們可以看出,在 SpringBoot 對 Redis 做了一系列的自動裝配,使用還是非常方便的
一、背景
1、思考
通過我們前面的學(xué)習(xí),我們已經(jīng)可以往 Redis 中存入字符串,那么我們要往 Redis 中存入 Java 對象該怎么辦呢?
2、方案
我們可以將 Java 對象轉(zhuǎn)化為 JSON 對象,然后轉(zhuǎn)為 JSON 字符串,存入 Redis,那么我們從 Redis 中取出該數(shù)據(jù)的時(shí)候,我們也只能取出字符串,并轉(zhuǎn)為 Java 對象,這一系列的操作是不是顯得有些麻煩呢?
二、源碼分析

- 以上是 RedisAutoConfiguration 類中的源碼片段,可以看出 SpringBoot 對 Redis 做自動化配置的時(shí)候,在容器中注入了 redisTemplate 和 stringRedisTemplate
- 其中,RedisTemplate<Object, Object> 表示,key 的類型為 Object,value 的類型為 Object,但是我們往往需要的是 RedisTemplate<String, Object>,這就需要我們重新注入一個(gè) RedisTemplate 的 Bean,它的泛型為 RedisTemplate<String, Object>,并設(shè)置 key,value 的序列化方式
- 看到這個(gè)@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate對象了,這個(gè)自動配置的RedisTemplate不會實(shí)例化。因此我們可以直接自己寫個(gè)配置類,配置RedisTemplate。
三、注入RedisTemplate
1、引入依賴
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>以上引入了 redis 的依賴,其余依賴請自行添加
2、Redis 連接信息
spring:
# Redis配置
redis:
host: 127.0.0.1
port: 6379
database: 10
jedis:
pool:
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
max-active: 50
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制)
max-wait: 3000ms
# 連接池中的最大空閑連接數(shù)
max-idle: 20
# 連接池中的最小空閑連接數(shù)
min-idle: 5
# 連接超時(shí)時(shí)間(毫秒)
timeout: 5000ms3、Redis 核心配置類
Redis 的核心配置我們放在 RedisConfig.java 文件中
package com.zyxx.redistest.common;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @ClassName RedisConfig
* @Description
* @Author Lizhou
* @Date 2020-10-22 9:48:48
**/
@Configuration
public class RedisConfig {
/**
* RedisTemplate配置
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 配置redisTemplate
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 設(shè)置序列化
Jackson2JsonRedisSerializer<Object> 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.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
// value序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// Hash key序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// Hash value序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
我們注入了一個(gè)名稱為 redisTemplate,類型為 RedisTemplate<String, Object> 的 Bean,key 采用 StringRedisSerializer 序列化方式,value 采用 Jackson2JsonRedisSerializer 序列化方式
4、Redis工具類
我們將對 Redis 進(jìn)行的一系列操作放在 RedisUtils.java 文件中
package com.zyxx.redistest.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* @ClassName RedisUtils
* @Description
* @Author Lizhou
* @Date 2020-10-22 10:10:10
**/
@Slf4j
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 根據(jù)key讀取數(shù)據(jù)
*/
public Object get(final String key) {
if (StringUtils.isBlank(key)) {
return null;
}
try {
return redisTemplate.opsForValue().get(key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 寫入數(shù)據(jù)
*/
public boolean set(final String key, Object value) {
if (StringUtils.isBlank(key)) {
return false;
}
try {
redisTemplate.opsForValue().set(key, value);
log.info("存入redis成功,key:{},value:{}", key, value);
return true;
} catch (Exception e) {
log.error("存入redis失敗,key:{},value:{}", key, value);
e.printStackTrace();
}
return false;
}
}
我們寫入了 get,set 兩個(gè)方法用于測試
四、測試
1、創(chuàng)建 Java 實(shí)體類 UserInfo
package com.zyxx.redistest.common;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName UserInfo
* @Description
* @Author Lizhou
* @Date 2020-10-22 10:12:12
**/
@Data
public class UserInfo implements Serializable {
/**
* id
*/
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 創(chuàng)建時(shí)間
*/
private Date createTime;
}2、測試用例
package com.zyxx.redistest;
import com.zyxx.redistest.common.RedisUtils;
import com.zyxx.redistest.common.UserInfo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest
class RedisTestApplicationTests {
@Autowired
private RedisUtils redisUtil;
@Test
void contextLoads() {
UserInfo userInfo = new UserInfo();
userInfo.setId(1);
userInfo.setName("jack");
userInfo.setCreateTime(new Date());
// 放入redis
redisUtil.set("user", userInfo);
// 從redis中獲取
System.out.println("獲取到數(shù)據(jù):" + redisUtil.get("user"));
}
}我們向 Redis 中存入了一個(gè) key 為 ”user“,value 為 UserInfo 對象的數(shù)據(jù),然后再根據(jù) key 獲取該數(shù)據(jù)
3、測試結(jié)果

可以看出,我們往 Redis 中成功存入 Java 對象數(shù)據(jù),并成功獲取到了該對象
到此這篇關(guān)于SpringBoot整合Redis實(shí)現(xiàn)序列化存儲Java對象的文章就介紹到這了,更多相關(guān)SpringBoot整合Redis序列化存儲Java對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Spring?Boot實(shí)現(xiàn)Redis鍵過期回調(diào)功能示例詳解
這篇文章主要介紹了使用Spring?Boot實(shí)現(xiàn)Redis鍵過期回調(diào)功能,就是一個(gè)實(shí)現(xiàn)Redis鍵過期回調(diào)功能的Spring?Boot應(yīng)用的示例,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Redis和springboot 整合redisUtil類的示例代碼
這篇文章主要介紹了Redis和springboot 整合redisUtil類的示例代碼,本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
利用redisson快速實(shí)現(xiàn)自定義限流注解(接口防刷)
利用redis的有序集合即Sorted?Set數(shù)據(jù)結(jié)構(gòu),構(gòu)造一個(gè)令牌桶來實(shí)施限流,而redisson已經(jīng)幫我們封裝成了RRateLimiter,通過redisson,即可快速實(shí)現(xiàn)我們的目標(biāo),這篇文章主要介紹了利用redisson快速實(shí)現(xiàn)自定義限流注解,需要的朋友可以參考下2024-07-07

