/**
 * Copyright (C), 2015-2020, XXX公司
 * FileName: JedisClusterConfig
 * Author:   hanyu
 * Date:     2020/03/23 9:54
 * Description:
 */
package com.aiup.service.utils;


import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * jedis 集群客户端配置
 *
 * @author: hy
 * @date: 2018/5/14
 */
@Lazy
@Configuration
public class JedisClusterConfig {
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.maxTotal}")
    private int maxTotal;

    @Value("${spring.redis.password}")
    private String password;

    /**
     * 注意：
     * 这里返回的JedisCluster是单例的，并且可以直接注入到其他类中去使用
     *
     * @return
     */
    @Bean
    public JedisCluster getJedisCluster() {
        //获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)
        String[] serverArray = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        //Timeout: 返回值的超时时间
        //maxAttempts：出现异常最大重试次数
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxTotal);

        if (StringUtils.isNotEmpty(password)) {
            return new JedisCluster(nodes, timeout, timeout, 3, password, poolConfig);
        } else {
            return new JedisCluster(nodes, timeout, 3, poolConfig);
        }
    }
}
