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

相关推荐
ALex_zry3 小时前
Redis Cluster 分布式缓存架构设计与实践
redis·分布式·缓存
tb_first3 小时前
LangChain4j简单入门
java·spring boot·langchain4j
乔江seven6 小时前
【Flask 进阶】3 从同步到异步:基于 Redis 任务队列解决 API 高并发与长耗时任务阻塞
redis·python·flask
这周也會开心7 小时前
Redis与MySQL回写中的数据类型存储设计
数据库·redis·mysql
计算机学姐7 小时前
基于SpringBoot的民宿预定管理系统【三角色+个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·mysql·信息可视化·intellij-idea·推荐算法
shuair7 小时前
redis缓存预热、缓存击穿、缓存穿透、缓存雪崩
redis·spring·缓存
计算机程序设计小李同学7 小时前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
LiZhen7988 小时前
SpringBoot 实现动态切换数据源
java·spring boot·mybatis
shuair8 小时前
guava布隆过滤器及cuckoo过滤器
redis·guava
上架ipa8 小时前
redis图形化客户端功能对比
redis·缓存