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

相关推荐
冼紫菜9 小时前
[特殊字符] 深入理解 PageHelper 分页原理:从 startPage 到 SQL 改写全过程
java·后端·sql·mysql·spring
番茄Salad10 小时前
Spring Boot项目中Maven引入依赖常见报错问题解决
spring boot·后端·maven
Jabes.yang10 小时前
Java求职面试: 互联网医疗场景中的缓存技术与监控运维应用
java·redis·spring security·grafana·prometheus·oauth2·互联网医疗
摇滚侠10 小时前
Spring Boot 3零基础教程,yml配置文件,笔记13
spring boot·redis·笔记
CryptoRzz10 小时前
越南k线历史数据、IPO新股股票数据接口文档
java·数据库·后端·python·区块链
QX_hao11 小时前
【Go】--数组和切片
后端·golang·restful
-睡到自然醒~11 小时前
提升应用性能:Go中的同步与异步处理
开发语言·后端·golang
文心快码BaiduComate11 小时前
新手该如何选择AI编程工具?文心快码Comate全方位体验
前端·后端·程序员
!if11 小时前
springboot mybatisplus 配置SQL日志,但是没有日志输出
spring boot·sql·mybatis
阿挥的编程日记11 小时前
基于SpringBoot的影评管理系统
java·spring boot·后端