Spring Data Redis 使用Lettuce在Redis集群中无法高可用

落爺英雄遲暮 提交于 2021-01-23 00:27:25

Spring Data Redis 使用Lettuce在Redis集群中无法高可用

Spring boot 2.1.X 下Spring-data-redis-start 使用 Lettuce 作为Redis连接池

问题场景

在App运行期间Redis集群中某个Master节点 Shutdown,导致应用连接Redis报错,错误信息 连接超时。

解决方案

Lettuce 解决方法

使用 RedisClusterClient.reloadPartitions 自动reload pattitions。

链接地址:https://lettuce.io/core/release/reference/index.html#redis-cluster.refreshing-the-cluster-topology-view

Spring-data-redis 解决方法

重写 RedisConnectionFactory Bean

@Data
@Component
public class RedisConfig {

    @Autowired
    RedisProperties redisProperties;


    @Bean
    public RedisConnectionFactory newLettuceConnectionFactory() {

        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                .enablePeriodicRefresh(Duration.ofSeconds(30))
                .enableAllAdaptiveRefreshTriggers()
                .build();
        ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                .validateClusterNodeMembership(false)
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build();
        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                .commandTimeout(redisProperties.getTimeout())
                .shutdownTimeout(Duration.ZERO)
                .clientOptions(clusterClientOptions)
                .build();

        RedisClusterConfiguration serverConfig = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());

        return new LettuceConnectionFactory(serverConfig, clientConfig);
    }

}

使用jedis 替换 lettuce 

pom 信息

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

lettuce 配置信息

spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-wait=10
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.shutdown-timeout=1S

jedis 配置信息

spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=10
spring.redis.jedis.pool.min-idle=5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!