【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 小时前
golang 查看指定版本库所依赖库的版本
开发语言·后端·golang
Mr__Miss6 小时前
Redis的持久化
数据库·redis·缓存
Codeking__7 小时前
Redis——基本通用命令
redis·git·github
程序员张39 小时前
Mybatis条件判断某属性是否等于指定字符串
java·spring boot·mybatis
invicinble10 小时前
从逻辑层面理解Shiro在JVM中是如何工作的
jvm·spring boot
Marktowin12 小时前
Mybatis-Plus更新操作时的一个坑
java·后端
赵文宇12 小时前
CNCF Dragonfly 毕业啦!基于P2P的镜像和文件分发系统快速入门,在线体验
后端
程序员爱钓鱼13 小时前
Node.js 编程实战:即时聊天应用 —— WebSocket 实现实时通信
前端·后端·node.js
@220613 小时前
银河麒麟系统离线环境下用docke方式部署(Postgres、Nginx、Redis、JDK)
运维·数据库·redis·nginx