【SpringBoot】在SpringBoot中配置序列化的Redis


前言

在使用Java操作Redis时,如果不对Redis进行序列化操作,可能会导致存储的key和value与原来的数据不一致的问题

本文也借此机会来详细讲解一下SpringBoot中配置序列化Redis的步骤

展示包结构

在这里插入图片描述


在SpringBoot中配置Redis

步骤:

  1. 导入maven依赖
  2. 编写配置文件
  3. 编写配置类注入ReidsTemplate
  4. 使用测试
  1. 导入maven坐标
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>2.7.3</version>
</dependency>

在这里插入图片描述


  1. 编写配置文件
#还有密码等配置,需要可自行添加
spring:
  redis:
    host: localhost
    port: 6379

在这里插入图片描述


  1. 编写redisconfiguration类注入redisTemplate的Bean
@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //我这里设置了键和值的序列化器,其余的都是一样的set...Serializer()
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

在这里插入图片描述

这一步完成后,可以选择将这个RedisTemplate封装成一个工具类,也可以在使用的时候使用@Autowired注解注入

测试

我在测试类里面测试,大家可以自行测试哦


@SpringBootTest
class SpringbootRedisTestApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void redisTest(){
        redisTemplate.opsForValue().set("name", "zhangsan");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }

在这里插入图片描述

可以看到结果返回出来的,然后我们再到redis客户端去查看,也可以看到输出是正常的

在这里插入图片描述

总结

再SpringBoot中配置redis就是这几步啦,我们想让Redis正常存储,就需要使用序列化,再配置RedisTemplate对象时设置序列化就可以了~

  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无技术,不人生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值