SpringBoot40-springboot中redis的对象操作

2025-06-06 15:50:07

1、使用【redisTemplate.opsForValue().set()】方法存储一个emp的对象,如下图:

SpringBoot40-springboot中redis的对象操作

2、运行这个springboot的测试方法,可以从控制台看到这里报错,错误是无法序列化,如下图:

SpringBoot40-springboot中redis的对象操作

3、打开employee的对象定义类,这里implements Serializable,如下图:

SpringBoot40-springboot中redis的对象操作

4、然后运行springboot项目的测试方法,成功,如下图:

SpringBoot40-springboot中redis的对象操作

5、然后打开redis的客户端,可以看到已经将emp保存到了redis中,但是此时保存的数据是序列化的数据,如下图:

SpringBoot40-springboot中redis的对象操作

6、我们在【RedisAutoConfiguration】类中查看返回的【RedisTemplate】,按着ctrl键点击【RedisTemplate】,如下图:

SpringBoot40-springboot中redis的对象操作

7、可以看到这个【RedisTemplate】默认使用的是java的【JdkSerializationRedisSerializer】,如下图:

SpringBoot40-springboot中redis的对象操作

8、然后在【RedisTemplate】中有一个【setDefaultSerial坡纠课柩izer】的方法,按着ctrl点击【R髫潋啜缅edisSerializer】,然后我们这里在自己的redisconfig的配置文件中设置redistemplate的序列化方式,如下图:

SpringBoot40-springboot中redis的对象操作

9、下图小编在springboot项目中的config文件夹中添加一个【MyRedisConfig】配置类,如下图:

SpringBoot40-springboot中redis的对象操作

10、然后这里创建【Jackson2JsonRedisSerializer】,然后将首疏扌熘创建的这个序列化设置到返回的【RedisTemplate】,如下图:

SpringBoot40-springboot中redis的对象操作

11、然后再次在测试方法中使用配置文件中的empredisTemplate将对象添加到redis,如下图:

SpringBoot40-springboot中redis的对象操作

12、控制台显示测试方法成功,如下图:

SpringBoot40-springboot中redis的对象操作

13、再次使用控制台查看redis,可以看到存入到redis中的数据已经是json数据格式了,如下图:

SpringBoot40-springboot中redis的对象操作
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢