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

文章目录


前言

在使用Java操作Redis时,如果不对Redis进行序列化操作,可能会导致存储的key和value与原来的数据不一致的问题
本文也借此机会来详细讲解一下SpringBoot中配置序列化Redis的步骤

展示包结构


在SpringBoot中配置Redis

步骤:

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

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

  1. 编写redisconfiguration类注入redisTemplate的Bean
java 复制代码
@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注解注入

测试

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

java 复制代码
@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对象时设置序列化就可以了~

相关推荐
行百里er5 小时前
2026:一名码农的“不靠谱”年度规划
后端·程序员·架构
全靠bug跑7 小时前
Spring Cache 实战:核心注解详解与缓存过期时间配置
java·redis·springcache
计算机程序设计小李同学8 小时前
基于SpringBoot的个性化穿搭推荐及交流平台
java·spring boot·后端
用户47949283569158 小时前
同事一个比喻,让我搞懂了Docker和k8s的核心概念
前端·后端
aloha_7899 小时前
agent智能体学习(尚硅谷,小智医疗)
人工智能·spring boot·python·学习·java-ee
li.wz10 小时前
Spring Bean 生命周期解析
java·后端·spring
sanggou10 小时前
【实战总结】Spring Boot 后端接口防抖详解与实现方案(含注解 + Redis)
spring boot·后端
虫小宝10 小时前
优惠券省钱app高并发秒杀系统:基于Redis与消息队列的架构设计
数据库·redis·缓存
Victor35611 小时前
Hibernate(26)什么是Hibernate的透明持久化?
后端
盖世英雄酱5813611 小时前
不是所有的this调用会导致事务失效
java·后端