> 文章列表 > Spring lettuce读写分离

Spring lettuce读写分离

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";@Beanpublic LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() {return builder -> builder.readFrom(SHENZHEN.equalsIgnoreCase(idc) ? ReadFrom.SLAVE_PREFERRED : ReadFrom.MASTER);}}

application 配置

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

ReadFrom 配置

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

Setting Description
MASTER Default mode. Read from the current master node.
MASTER_PREFERRED Read from the master, but if it is unavailable, read from replica nodes.
REPLICA Read from replica nodes.
REPLICA_PREFERRED Read from the replica nodes, but if none is unavailable, read from the master.
LOWEST_LATENCY Read from any node of the cluster with the lowest latency.
ANY Read from any node of the cluster.
ANY_REPLICA Read from any replica of the cluster.

参考文档:

  1. SpringBoot中Redis Sentinel模式下读写分离
  2. Read from settings