springboot整合redis集群master宕机后连接超时

4 篇文章 0 订阅
1 篇文章 0 订阅

前提:

#        本文是在确保redis集群配置正确的情况下,连接超时的解决方案。

        项目登录认证使用的是sa-token(这个不重要,主要说的是springboot和redis集群),最近应甲方要求,需要做redis集群,在测试主从切换的时候发现,redis的master虽然切换过来了,但是springboot连接redis还是请求的之前宕掉的节点ip,没有更新过来。

原因:

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

解决方案:

        方案一、把lettuce换成jedis(我用的这个,亲测好使)

 #        切换jedis有个问题,就是在master宕机,cluster升为master期间,15秒内还是会报连接超时,15秒后项目正常了,项目流量大的慎用。

        <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>

方案二:(这个是网上摘得,没有做测试,各位大佬有时间可以试试)

    @Autowired
	private RedisProperties redisProperties;
 
	@Bean
	public GenericObjectPoolConfig<?> genericObjectPoolConfig(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.getLettuce().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;
	}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值