Spring Boot 整合 Redis 集群详解

本文详细描述了如何在SpringBoot项目中集成Redis,包括配置步骤、遇到的NoClassDefFoundError错误原因及解决方法,重点讨论了序列化问题的处理,提供了RedisTemplate的使用示例和常见问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

项目中需要使用 Redis 做缓存数据库,本文分享一下 Spring Boot 项目集成 Redis 的过程以及踩过的坑。

Spring Boot 集成 Redis 可以分为三大步,如下:

  • 在 proerties 或者 yml 文件中添加 redis 和 lettuce 配置。
  • 项目 pom.xml 文件中引入 spring-boot-starter-data-redis 依赖。
  • 注入 RedisTemplate 开始使用 Redis,其实这步以及算是使用了,不能算作集成了,但是集成了总归是要使用的,我把这里也算作一步了。

添加 redis 和 lettuce 配置:

//redis 集群地址
spring.redis.cluster.nodes = dev-k8s-redis.eminxing.com:17000
//密码
spring.redis.password = z8_UX7BCi_XYckrM
//在群集上执行命令时重定向的最大数量。
spring.redis.cluster.max-redirects = 3
//连接池最小空闲连接数 负值表示没有限制
spring.redis.lettuce.pool.max-idle = 10
//连接池最大空闲连接数 负值表示没有限制
spring.redis.lettuce.pool.min-idle = 5
//连接池最大活跃连接数 负值表示没有限制
spring.redis.lettuce.pool.max-active = 20
//建立连接最大等待时间,默认1ms,超出该时间会抛异常。设为-1表示无限等待,直到分配成功
spring.redis.lettuce.pool.max-wait = 10000

以上配置,会自动由 Spring Boot 自动装配,不需要再配置类,Spring Boot 会自动把这些配置参数加载后实例化连接池。

项目 pom.xml 文件中引入 spring-boot-starter-data-redis 依赖:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

注入 RedisTemplate 开始使用 Redis,启动就报错,完美翻车,错误信息如下:

nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig

关于这个错误的解决方案另起了一篇文章进行了详细分析,如下:

解决报错传送门:

传送门告诉我们正确的 Spring Boot 2.0 以上版本集成 Redis 的正确依赖如下:

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-pool2</artifactId>
</dependency>

解决启动报错问题,准备开始使用:

测试代码:

@Slf4j
@RestController
@RequestMapping("/api/redis/")
public class RedisDemoController {
   

    @Autowired
    private RedisUtils redisUtils;

    @ApiOperation(value = "测试redis", produces = "application/json")
    @GetMapping("/test-redis")
    public Result<String> batchCreateOrUpdatePipeline(@RequestParam("key") String key, @RequestParam("value") String value) {
   
        redisUtils.set(key, value);
        return ResultGenerator.genSuccessResult();
    }
}

这里的 RedisUtils 是我封装的一个工具类,下文会进行分享,这里先分享一下演示结果,Another Redis Desktop Manager 客户端展示如下:

在这里插入图片描述
分析结果,我们发现出现了一串字符串 “\xac\xed\x00\x05t\x00\x10”,这串字符串明显不是我们想要看到的,难道是 Redis 集成又出问题了吗,使用代码获取了缓存字符串,发现并没有这串奇奇怪怪的字符串,那是怎么回事呢?查阅资料得知是序列话的问题。

Redis 序列化与反序列化问题处理,如下:

@Configuration
public class RedisConfig {
   

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
   
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        serializer.setObjectMapper(mapper);

        //如果不序列化在key value 使用redis客户端工具 直连redis服务器 查看数据时 前面会有一个 \xac\xed\x00\x05t\x00\x05 字符串
        // StringRedisSerializer 来序列化和反序列化 String 类型 redis 的 key value
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        // StringRedisSerializer 来序列化和反序列化 hash 类型 redis 的 key value
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

自定义了 RedisTemplate 配置,设置了序列化和反序列化后,再次验证后,如下:
在这里插入图片描述
完美解决问题。

RedisUtils 分享如下:

package com.zt.zteam.main.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值