Redis集群Lettuce主从切换问题解决方案

 更新时间:2023年07月09日 11:42:06   作者:AC编程  
这篇文章主要为大家介绍了Redis集群Lettuce主从切换问题解决方案,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

一、问题描述

Redis Cluster集群,当master宕机,主从切换,客户端报错 timed out

二、原因

SpringBoot2.X版本开始Redis默认的连接池都是采用的Lettuce。当节点发生改变后,Letture默认是不会刷新节点拓扑的。

三、解决方案

3.1 方案一:把lettuce换成jedis

只需要在pom.xml里调整一下依赖的引用

      <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
           <version>2.1.5.RELEASE</version>
               <!-- 不用lettuce ,用jedis -->
               <exclusions>
                   <exclusion>
                       <groupId>io.lettuce</groupId>
                       <artifactId>lettuce-core</artifactId>
                   </exclusion>
               </exclusions>
       </dependency>
       <dependency>
           <groupId>redis.clients</groupId>
           <artifactId>jedis</artifactId>
           <version>3.1.0-m4</version>
       </dependency>

3.2 方案二:刷新节点拓扑视图

Redis节点异常,服务端的Redis集群拓扑被刷新了,Java程序没有获取到新的拓扑。

Lettuce官方文档中关于Redis Cluster的相关说明:Lettuce处理Moved和Ask永久重定向,由于命令重定向,你必须刷新节点拓扑视图。而自适应拓扑刷新(Adaptive updates)与定时拓扑刷新(Periodic updates)是默认关闭的,可以通过如下代码打开。

https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster#user-content-refreshing-the-cluster-topology-view

修改代码如下

package com.montnets.common.redis;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
public class RedisPoolConfig {
    @Autowired
    private RedisProperties redisProperties;
    public GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Pool properties) {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(properties.getMaxActive());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMinIdle(properties.getMinIdle());
        if (properties.getTimeBetweenEvictionRuns() != null) {
            config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
        }
        if (properties.getMaxWait() != null) {
            config.setMaxWaitMillis(properties.getMaxWait().toMillis());
        }
        return config;
    }
    @Bean(destroyMethod = "destroy")
    public LettuceConnectionFactory lettuceConnectionFactory() {
        //开启 自适应集群拓扑刷新和周期拓扑刷新
        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions =  ClusterTopologyRefreshOptions.builder()
                // 开启全部自适应刷新
                .enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
                // 自适应刷新超时时间(默认30秒)
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(30)) //默认关闭开启后时间为30秒
                // 开周期刷新
                .enablePeriodicRefresh(Duration.ofSeconds(20))  // 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                .build();
        // https://github.com/lettuce-io/lettuce-core/wiki/Client-Options
        ClientOptions clientOptions = ClusterClientOptions.builder()
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build();
        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .poolConfig(genericObjectPoolConfig(redisProperties.getJedis().getPool()))
                //.readFrom(ReadFrom.MASTER_PREFERRED)
                .clientOptions(clientOptions)
                .commandTimeout(redisProperties.getTimeout()) //默认RedisURI.DEFAULT_TIMEOUT 60
                .build();
        List<String> clusterNodes = redisProperties.getCluster().getNodes();
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        clusterNodes.forEach(address -> nodes.add(new RedisNode(address.split(":")[0].trim(), Integer.valueOf(address.split(":")[1]))));
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        clusterConfiguration.setClusterNodes(nodes);
        clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfiguration, clientConfig);
        // lettuceConnectionFactory.setShareNativeConnection(false); //是否允许多个线程操作共用同一个缓存连接,默认true,false时每个操作都将开辟新的连接
        // lettuceConnectionFactory.resetConnection(); // 重置底层共享连接, 在接下来的访问时初始化
        return lettuceConnectionFactory;
    }
}

以上就是Redis集群Lettuce主从切换问题解决方案的详细内容,更多关于Redis集群Lettuce主从切换的资料请关注脚本之家其它相关文章!

相关文章

  • Redis全文搜索教程之创建索引并关联源数据的教程

    Redis全文搜索教程之创建索引并关联源数据的教程

    RediSearch提供了一种简单快速的方法对 hash 或者 json 类型数据的任何字段建立二级索引,然后就可以对被索引的 hash 或者 json 类型数据字段进行搜索和聚合操作,这篇文章主要介绍了Redis全文搜索教程之创建索引并关联源数据,需要的朋友可以参考下
    2023-12-12
  • 基于Redis 实现网站PV/UV数据统计

    基于Redis 实现网站PV/UV数据统计

    PV和UV是两个重要的指标,本文主要介绍了基于Redis 实现网站PV/UV数据统计,具有一定的参考价值,感兴趣的可以了解一下
    2025-04-04
  • Redis实现短信验证码登录的示例代码

    Redis实现短信验证码登录的示例代码

    本文主要介绍了基于Redis如何实现短信验证码登录功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • 如何自定义redis工具jar包供其他SpringBoot项目直接使用

    如何自定义redis工具jar包供其他SpringBoot项目直接使用

    这篇文章主要介绍了如何自定义redis工具jar包供其他SpringBoot项目直接使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Redis中一些最常见的面试问题总结

    Redis中一些最常见的面试问题总结

    Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行各种刁难。下面这篇文章主要给大家总结介绍了关于Redis中一些最常见的面试问题,需要的朋友可以参考下
    2018-09-09
  • Redis缓存工具封装实现

    Redis缓存工具封装实现

    本文主要介绍了Redis缓存工具封装实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • CentOS系统安装Redis及Redis的PHP扩展详解

    CentOS系统安装Redis及Redis的PHP扩展详解

    这篇文章主要介绍了CentOS系统下安装Redis数据的教程,以及详解了Redis数据库的PHP扩展,文中介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-12-12
  • Redis哨兵模式实现一主二从三哨兵

    Redis哨兵模式实现一主二从三哨兵

    本文主要介绍了Redis哨兵模式实现一主二从三哨兵,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • Redis连接错误的情况总结分析

    Redis连接错误的情况总结分析

    这篇文章主要给大家总结介绍了关于Redis连接错误的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-02-02
  • Redis数据库的安装配置方法

    Redis数据库的安装配置方法

    redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类keyvalue存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。它提供了Python,Ruby,Erlang,PHP客户端,使用很方便
    2014-06-06

最新评论