Spring lettuce读写分离

Redis 的 Sentinel 模式默认配置下 Redis 的客户端只对 Master 读写,另外2个Slave闲置。若主从节点在不同机房,在读取时会有跨机房的网络时延,并且比同机房访问更容易发生网络丢包。故在一些场景可以考虑将跨机房的服务节点设置为读写分离

Redis 的 Sentinel 模式下最少是一主二从,不算 Sentinel 节点要占用3个节点

读写分离配置

{@link org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration}

在这里插入图片描述

低版本为ReadFrom.SLAVE_PREFERRED,高版本为REPLICA_PREFERRED。作用为在从节点读取,若无可用从节点,则在主节点读取

LettuceClientConfiguration

@Configuration
public class LettuceClientConfiguration {

    @Value("${app.idc:}")
    private String idc;
    public static final String SHENZHEN = "shenzhen";

    @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() {
        return builder -> builder.readFrom(SHENZHEN.equalsIgnoreCase(idc) ? ReadFrom.SLAVE_PREFERRED : ReadFrom.MASTER);
    }

}

application 配置

spring:
  redis:
    sentinel:
      master: newredis_001
      nodes: wx-sentinel.test.com:20071,sz-sentinel.test.com:20071
    timeout: 600ms
    lettuce:
      pool:
        max-active: 200
        min-idle: 5
        max-idle: 50
        time-between-eviction-runs: 300s
        max-wait: 500ms

ReadFrom 配置

所有除了MASTER外的ReadFrom配置都可能返回旧数据。因为副本复制是异步的,并且需要一些延迟

SettingDescription
MASTERDefault mode. Read from the current master node.
MASTER_PREFERREDRead from the master, but if it is unavailable, read from replica nodes.
REPLICARead from replica nodes.
REPLICA_PREFERREDRead from the replica nodes, but if none is unavailable, read from the master.
LOWEST_LATENCYRead from any node of the cluster with the lowest latency.
ANYRead from any node of the cluster.
ANY_REPLICARead from any replica of the cluster.

参考文档:

  1. SpringBoot中Redis Sentinel模式下读写分离
  2. Read from settings
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值