package org.springblade.common.cache.support;

import java.util.ArrayList;
import java.util.List;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

@Slf4j
@Configuration
public class CacheConfig {
	
	@Value("${redis.cache.conn.host}")
	@Setter
	private String redisHost;
	
	@Value("${redis.cache.conn.port}")
	@Setter
	private int redisPort;
	
	@Value("${redis.cache.conn.password}")
	@Setter
	private String redisPassword;
	
	@Value("${redis.cache.conn.timeout:5000}")
	@Setter
	private int redisTimeout;

	@Setter
	@Value("${redis.cache.conn.max-total:8}")
	private int poolMaxTotal;
	@Setter
	@Value("${redis.cache.conn.min-idle:0}")
	private int poolMinIdle;
	@Setter
	@Value("${redis.cache.conn.max-idle:8}")
	private int poolMaxIdle;
	@Setter
	@Value("${redis.cache.conn.test-on-borrow:false}")
	private boolean redisTestOnBorrow;

	@Bean
	public ShardedJedisPool shardedJedisPool() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxWaitMillis(redisTimeout);
		config.setMaxTotal(poolMaxTotal);
		config.setMinIdle(poolMinIdle);
		config.setMaxIdle(poolMaxIdle);
		config.setTestOnBorrow(redisTestOnBorrow);
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		JedisShardInfo server1 = new JedisShardInfo(redisHost, redisPort, "server1");
		if (!StringUtils.isEmpty(redisPassword)) {
			server1.setPassword(redisPassword);
		}
		shards.add(server1);
		//shards.add(new JedisShardInfo("ip2", 6379, "server2"));
		ShardedJedisPool jedisPool = new ShardedJedisPool(config, shards);
		log.info("用于缓存的Redis连接池配置为: 最大连接数-{}, 最大空闲连接数-{}", poolMaxTotal, poolMaxIdle);
		return jedisPool;
	}
	

}
