package com.yeejoin.amos.maintenance.config;
import com.yeejoin.amos.boot.biz.config.RedisConfigProperties;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.time.Duration;


@Configuration
public class RedisClusterConfig {
    @Autowired
    private RedisConfigProperties redisConfigProperties;
    @Bean
    @ConditionalOnProperty(name = "spring.redis.mode", havingValue = "cluster")
    public RedisConnectionFactory redisConnectionFactory() {
        // 开启自适应集群拓扑刷新和周期拓扑刷新，不开启相应槽位主节点挂掉会出现服务不可用，直到挂掉节点重新恢复
        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions =  ClusterTopologyRefreshOptions.builder()
                .enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(30)) //自适应刷新超时时间(默认30秒)，默认关闭开启后时间为30秒
                .enablePeriodicRefresh(Duration.ofSeconds(20))  // 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                .build();
        ClientOptions clientOptions = ClusterClientOptions.builder()
                .topologyRefreshOptions(clusterTopologyRefreshOptions)
                .build();
        // 客户端读写分离配置
        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                .clientOptions(clientOptions)
                .build();
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(
                redisConfigProperties.getCluster().getNodes());
        if (StringUtils.isNotBlank(redisConfigProperties.getPassword())) {
            redisClusterConfiguration.setPassword(redisConfigProperties.getPassword());
        }
        return new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);
    }
}

