Redis主从架构配置 读写分离

在 Spring Boot 中实现 Redis 读请求的分摊负载(将读操作分散到多个从节点),需要通过 Redis客户端配置读写分离策略 来实现。以下是具体实现步骤与配置示例:


1. 基础环境准备

确保 Redis 主从架构已正确部署
  • 主节点:127.0.0.1:6379
  • 从节点:127.0.0.1:6380, 127.0.0.1:6381
项目依赖
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId> <!-- 推荐使用Lettuce客户端 -->
</dependency>

2. 核心配置:Lettuce客户端实现读写分离(配置好无需关心什么是读什么是写,和之前写法一样,Lettuce客户端会帮你实现的)

2.1 配置主从节点信息
# application.yml
spring:
  redis:
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 2
    # 配置所有节点(主+从)  
    cluster:
      nodes:
        - 127.0.0.1:6379
        - 127.0.0.1:6380
        - 127.0.0.1:6381
    # 启用读写分离模式(关键配置!)
    read-from: REPLICA_PREFERRED
配置项说明:
  • read-from: 定义读请求的路由策略
    • REPLICA_PREFERRED (推荐):优先从节点读取,主节点仅作备用
    • REPLICA:强制从从节点读取(主节点不参与读)
    • MASTER:强制从主节点读取(默认)

2.2 Redis 服务端建立主从
主节点 (6379) 从节点1 (6380) 从节点2 (6381) 发送PSYNC命令请求同步 返回RDB快照+复制流 发送PSYNC命令请求同步 返回RDB快照+复制流 主节点 (6379) 从节点1 (6380) 从节点2 (6381)
2.3客户端识别主从
Lettuce客户端 任意Redis节点(如6380) Master Slave1 Slave2 连接初始节点(配置列表中任意一个) 返回INFO replication信息 根据INFO识别主节点地址 记录从节点信息 记录从节点信息 Lettuce客户端 任意Redis节点(如6380) Master Slave1 Slave2

3. 验证读写分离效果

3.1 注入 RedisTemplate
@Service
public class RedisService {
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
3.2 执行读写测试
@SpringBootTest
public class RedisReadWriteTest {

    @Autowired
    private RedisService redisService;

    @Test
    void testReadDistribution() {
        // 写操作(自动路由到主节点)
        redisService.redisTemplate.opsForValue().set("stress_test", "data");

        // 循环读操作(应分散到多个从节点)
        for (int i = 0; i < 100; i++) {
            String value = redisService.redisTemplate.opsForValue().get("stress_test");
            System.out.println("Read value: " + value);
        }
    }
}

4. 高级配置:自定义负载均衡策略

如果需要更精细的流量控制,可自定义 ReadFrom 策略:

4.1 创建自定义路由策略
import io.lettuce.core.ReadFrom;

@Configuration
public class RedisConfig {

    @Bean
    public LettuceClientConfigurationBuilderCustomizer customReadFrom() {
        return clientConfigurationBuilder -> 
            clientConfigurationBuilder.readFrom(
                ReadFrom.REPLICA_PREFERRED // 可替换为自定义策略
            );
    }
}
4.2 支持动态权重分配(示例)
// 自定义权重路由(需继承AbstractRedisClientConfiguration)
public class WeightedReadFromStrategy extends ReadFrom {

    @Override
    public List<RedisNodeDescription> select(Nodes nodes) {
        List<RedisNodeDescription> replicas = nodes.getNodes().stream()
                .filter(node -> node.getRole() == RedisInstance.Role.SLAVE)
                .collect(Collectors.toList());

        // 实现自定义权重算法(示例:70%流量到第一个从节点)
        return Collections.singletonList(replicas.get(0));
    }
}

5. 监控与验证手段

5.1 查看客户端连接分布
# 登录Redis从节点查看客户端连接数
redis-cli -p 6380 info clients | grep connected_clients
redis-cli -p 6381 info clients | grep connected_clients
5.2 使用Redis监控命令
# 查看主节点接收的请求类型
redis-cli -p 6379 info stats | grep -E "total_commands_processed|total_reads_processed|total_writes_processed"
5.3 Spring Boot Actuator 集成
# application.yml
management:
  endpoints:
    web:
      exposure:
        include: "redis"

访问 http://localhost:8080/actuator/redis 查看连接池状态。


6. 生产环境最佳实践

6.1 安全增强配置
spring:
  redis:
    password: your_redis_password
    ssl: true  # 启用TLS加密(Redis 6.0+)
6.2 故障转移处理
// 配置 Sentinel 实现自动故障转移
spring:
  redis:
    sentinel:
      master: mymaster
      nodes: 127.0.0.1:26379,127.0.0.1:26380
6.3 性能优化参数
spring:
  redis:
    lettuce:
      shutdown-timeout: 200ms
      pool:
        max-wait: 50ms
        time-between-eviction-runs: 60s

关键配置总结

配置项作用说明推荐值
spring.redis.read-from定义读请求路由策略REPLICA_PREFERRED
lettuce.pool.max-active控制最大连接数避免过载根据业务压力调整(建议8-16)
ReadFrom.REPLICA强制从从节点读取适用于纯读场景
ReadFrom.MASTER强制从主节点读取(默认)需要强一致性时使用

通过上述配置,Spring Boot 应用会自动将写操作定向到主节点,读操作根据策略分配到多个从节点。实际生产环境中,建议结合负载均衡器(如Nginx)或服务网格(如Istio) 实现更细粒度的流量控制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值