SpringBoot怎么整合Redis实现序列化存储Java对象

免费教程   2024年05月10日 5:17  

今天小编给大家分享一下SpringBoot怎么整合Redis实现序列化存储Java对象的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

一、背景1、思考

通过我们前面的学习,我们已经可以往 中存入字符串,那么我们要往 中存入 Java 对象该怎么办呢?

2、方案

我们可以将 Java 对象转化为 JSON 对象,然后转为 JSON 字符串,存入 Redis,那么我们从 Redis 中取出该数据的时候,我们也只能取出字符串,并转为 Java 对象,这一系列的操作是不是显得有些麻烦呢?

二、源码分析

以上是 RedisAutoConfiguration 类中的源码片段,可以看出 对 Redis 做自动化配置的时候,在容器中注入了 redisTemplate 和 stringRedisTemplate

其中,RedisTemplate<Object, Object> 表示,key 的类型为 Object,value 的类型为 Object,但是我们往往需要的是 RedisTemplate<String, Object>,这就需要我们重新注入一个 RedisTemplate 的 Bean,它的泛型为 RedisTemplate<String, Object>,并设置 key,value 的序列化方式

看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。

三、注入RedisTemplate1、引入依赖<!--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.1port:6379database:10jedis:pool:#连接池最大连接数(使用负值表示没有限制)max-active:50#连接池最大阻塞等待时间(使用负值表示没有限制)max-wait:3000ms#连接池中的最大空闲连接数max-idle:20#连接池中的最小空闲连接数min-idle:5#连接超时时间(毫秒)timeout:5000ms3、Redis 核心配置类

Redis 的核心配置我们放在 RedisConfig.java 文件中

packagecom.zyxx.redistest.common;importcom.fasterxml.jackson.annotation.JsonAutoDetect;importcom.fasterxml.jackson.annotation.PropertyAccessor;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.StringRedisSerializer;/***@ClassNameRedisConfig*@Description*@AuthorLizhou*@Date2020-10-229:48:48**/@ConfigurationpublicclassRedisConfig{/***RedisTemplate配置*/@BeanpublicRedisTemplate<Object,Object>redisTemplate(RedisConnectionFactoryredisConnectionFactory){//配置redisTemplateRedisTemplate<Object,Object>redisTemplate=newRedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);//设置序列化Jackson2JsonRedisSerializer<Object>jackson2JsonRedisSerializer=newJackson2JsonRedisSerializer<>(Object.class);ObjectMapperom=newObjectMapper();om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL,JsonTypeInfo.As.PROPERTY);jackson2JsonRedisSerializer.setObjectMapper(om);//key序列化redisTemplate.setKeySerializer(newStringRedisSerializer());//value序列化redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);//Hashkey序列化redisTemplate.setHashKeySerializer(newStringRedisSerializer());//Hashvalue序列化redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();returnredisTemplate;}}

我们注入了一个名称为 redisTemplate,类型为 RedisTemplate<String, Object> 的 Bean,key 采用 StringRedisSerializer 序列化方式,value 采用 Jackson2JsonRedisSerializer 序列化方式

4、Redis工具类

我们将对 Redis 进行的一系列操作放在 RedisUtils.java 文件中

packagecom.zyxx.redistest.common;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.stereotype.Component;/***@ClassNameRedisUtils*@Description*@AuthorLizhou*@Date2020-10-2210:10:10**/@Slf4j@ComponentpublicclassRedisUtils{@AutowiredprivateRedisTemplate<String,Object>redisTemplate;/***根据key读取数据*/publicObjectget(finalStringkey){if(StringUtils.isBlank(key)){returnnull;}try{returnredisTemplate.opsForValue().get(key);}catch(Exceptione){e.printStackTrace();}returnnull;}/***写入数据*/publicbooleanset(finalStringkey,Objectvalue){if(StringUtils.isBlank(key)){returnfalse;}try{redisTemplate.opsForValue().set(key,value);log.info("存入redis成功,key:{},value:{}",key,value);returntrue;}catch(Exceptione){log.error("存入redis失败,key:{},value:{}",key,value);e.printStackTrace();}returnfalse;}}

我们写入了 get,set 两个方法用于测试

四、测试1、创建 Java 实体类 UserInfopackagecom.zyxx.redistest.common;importlombok.Data;importjava.io.Serializable;importjava.util.Date;/***@ClassNameUserInfo*@Description*@AuthorLizhou*@Date2020-10-2210:12:12**/@DatapublicclassUserInfoimplementsSerializable{/***id*/privateIntegerid;/***姓名*/privateStringname;/***创建时间*/privateDatecreateTime;}2、测试用例packagecom.zyxx.redistest;importcom.zyxx.redistest.common.RedisUtils;importcom.zyxx.redistest.common.UserInfo;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importjava.util.Date;@SpringBootTestclassRedisTestApplicationTests{@AutowiredprivateRedisUtilsredisUtil;@TestvoidcontextLoads(){UserInfouserInfo=newUserInfo();userInfo.setId(1);userInfo.setName("jack");userInfo.setCreateTime(newDate());//放入redisredisUtil.set("user",userInfo);//从redis中获取System.out.println("获取到数据:"+redisUtil.get("user"));}}

我们向 Redis 中存入了一个 key 为 ”user“,value 为 UserInfo 对象的数据,然后再根据 key 获取该数据

3、测试结果

可以看出,我们往 Redis 中成功存入 Java 对象数据,并成功获取到了该对象。

以上就是“SpringBoot怎么整合Redis实现序列化存储Java对象”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部