Spring Boot + Redis Cluster 测试

🌟 Spring Boot + Redis Cluster 测试全指南

Redis Cluster 是 Redis 提供的原生分片和高可用方案。在 Spring Boot 项目中,我们通常使用 Spring Data Redis + Lettuce/Jedis 来连接 Cluster,实现自动分片、故障切换和高可用访问。本文将手把手讲解如何搭建一个 Spring Boot + Redis Cluster 测试案例。


📌 一、项目环境

  • Spring Boot 3.5.x
  • JDK 17+
  • Maven 或 Gradle
  • Redis Cluster(3 主 3 从,本教程假设端口 7000~7005)
  • Lettuce 客户端(Spring Boot 默认)

Docker Compose 安装 Redis 集群(三主三从)


📦 二、项目结构

复制代码
springboot-redis-cluster/
├─ src/
│  ├─ main/
│  │  ├─ java/com/example/rediscluster/
│  │  │  ├─ RedisClusterApplication.java
│  │  │  ├─ config/RedisConfig.java
│  │  │  └─ service/RedisService.java
│  │  └─ resources/
│  │     └─ application.yml
└─ pom.xml
  • Spring Boot + Redis Cluster 访问流程
  1. 获取 RedisTemplate / LettuceClusterConnection 2. 查询 key 所在 slot 3. 定位对应 Master 节点 4. 执行读写操作 5. 主节点复制数据 6. 返回结果 MOVED / ASK 重定向 Spring Boot 应用 Lettuce Cluster Client Redis Cluster Slot Table Redis Master 节点 Master 数据存储 Slave 从节点

📝 三、配置文件

1️⃣ Maven 依赖

xml 复制代码
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Redis Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2️⃣ application.yml 配置

yaml 复制代码
spring:
  data:
    redis:
      timeout: 5000ms
      cluster:
        max-redirects: 3
        nodes:
          - 192.168.3.150:7000
          - 192.168.3.150:7001
          - 192.168.3.150:7002
          - 192.168.3.150:7003
          - 192.168.3.150:7004
          - 192.168.3.150:7005
🔹 配置说明
配置项 作用
nodes Redis Cluster 节点列表
max-redirects 当遇到 MOVED 或 ASK 重定向时,客户端最大重试次数
timeout 连接超时时间

为什么这么配置

  • Cluster 节点列表必须包含所有主节点(最好加上从节点以提高容错)
  • max-redirects 避免无限循环重定向

🔧 四、Redis 配置类

java 复制代码
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        // 配置集群节点
        RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration()
                .clusterNode("192.168.3.150", 7000)
                .clusterNode("192.168.3.150", 7001)
                .clusterNode("192.168.3.150", 7002)
                .clusterNode("192.168.3.150", 7003)
                .clusterNode("192.168.3.150", 7004)
                .clusterNode("192.168.3.150", 7005);
        clusterConfig.setMaxRedirects(3); // 最大重定向次数
        return new LettuceConnectionFactory(clusterConfig);
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 使用 String 序列化 key/value
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

为什么这么配置

  • RedisClusterConfiguration 指定集群节点,客户端会自动处理 MOVED/ASK 重定向
  • LettuceConnectionFactory 支持线程安全和连接池
  • RedisTemplate 使用 String 序列化保证 key/value 可读性

💡 五、Redis Service 示例

java 复制代码
package com.example.rediscluster.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    private final RedisTemplate<String, String> redisTemplate;

    public RedisService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setValue(String key, String value, long timeoutSeconds) {
        redisTemplate.opsForValue().set(key, value, timeoutSeconds, TimeUnit.SECONDS);
    }

    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public boolean exists(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }
}

🧪 六、测试案例

java 复制代码
package com.example.rediscluster;

import com.example.rediscluster.service.RedisService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import jakarta.annotation.Resource;

@SpringBootTest
public class RedisClusterTest {

    @Resource
    private RedisService redisService;

    @Test
    public void testRedisCluster() {
        String key = "test-key";
        String value = "hello-cluster";

        // 写入
        redisService.setValue(key, value, 60);

        // 读取
        String result = redisService.getValue(key);
        System.out.println("读取结果: " + result);

        // 检查存在
        boolean exists = redisService.exists(key);
        System.out.println("是否存在: " + exists);

        // 删除
        redisService.delete(key);
        boolean existsAfterDelete = redisService.exists(key);
        System.out.println("删除后是否存在: " + existsAfterDelete);
    }
}

✅ 说明:

  • 无需关心具体 key 落在哪个节点,客户端会自动处理 Cluster 重定向
  • 适合测试集群写入、读取和高可用特性

查看数据,进入到 7000,7004 主从,其他节点没有。


🔹 七、注意事项

  1. 不要只连接单节点
    • Cluster 模式必须至少指定一个主节点,最好列出多个节点提高容错
  2. MOVED/ASK 自动处理
    • Lettuce/Jedis 都会自动处理,无需手动跳转
  3. 连接池配置
    • 高并发场景下必须配置连接池,避免线程阻塞
  4. 数据分片透明化
    • Redis Cluster 客户端对应用透明,应用不需要关心槽位映射

🎯 八、总结

  • 本文搭建了 Spring Boot + Redis Cluster 测试案例
  • 完整演示了:
    • 配置 Redis Cluster 节点
    • 使用 Lettuce 连接 Spring Boot
    • RedisTemplate 操作 key/value
    • Cluster-aware 写入与读取
  • 讲解了 为什么这么配置
    • 最大重定向保证数据写入正确节点
    • 连接池优化性能
    • 集群客户端自动处理主从切换和故障

通过这种方式,应用可以透明、安全地使用 Redis Cluster,实现分布式缓存和高可用特性,非常适合生产环境和测试环境使用。