package com.ssj.framework.core.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;

@Configuration
@EnableRedisHttpSession
public class RedisConfig {



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

    @Value("${spring.redis.cluster.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.cluster.pool.max-wait}")
    private long maxWaitMillis;


    @Value("${spring.redis.block-when-exhausted}")
    private boolean  blockWhenExhausted;

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

    @Bean
    public JedisCluster redisPoolFactory()  throws Exception{
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);
        String[] cNodes = clusterNodes.split(",");
        HashSet<HostAndPort> nodes = new HashSet<>();
        //分割集群节点
        for (String node : cNodes) {
            String[] hp = node.split(":");
            nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
        }
        //创建集群对象
       // JedisCluster jedisCluster = new JedisCluster(nodes, timeout, jedisPoolConfig);

        return  new JedisCluster(nodes,timeout,timeout,5,password, jedisPoolConfig);
      //  return  new JedisCluster(nodes, timeout, jedisPoolConfig);
    }

}