【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对象时设置序列化就可以了~

相关推荐
计算机学姐6 分钟前
基于SpringBoot的旅游系统的设计与实现
java·vue.js·spring boot·后端·spring·java-ee·旅游
她说..6 分钟前
Redis项目实战整理
数据库·redis·缓存
卷心菜的学习路10 分钟前
Spring Boot 多数据源落地:AbstractRoutingDataSource + 注解切面(附源码)
java·spring boot·后端
薄雾晚晴22 分钟前
大模型Skill暴论:所有Skill终将消亡?最新Skill方法论与模型增强开发实战
前端·后端·架构
MacroZheng41 分钟前
面试官皱眉:"你懂 Vibe Coding,那你说superpowers和grill-me怎么选?",我:"小孩才做选择,我全都要!"
java·人工智能·后端
武哥聊编程1 小时前
【AI实战项目】基于SpringAI+Springboot+Vue的AI智能简历优化助手
vue.js·人工智能·spring boot
千里码aicood1 小时前
flask-基于注意力机制的异常流量检测与自动防御系统
后端·python·flask
李迟1 小时前
Golang实践录:工程框架实践:搭建工程模板
开发语言·后端·golang
Lynko1 小时前
C语言指针高阶
后端
the局外人1 小时前
学习 FastAPI 的 Day 2:用异步 ORM 完成增删改查
后端·python·fastapi