package cn.basics.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @ClassName: RedisUtil
 * @Description: TODO(Redis连接池工具)
 * @author zhiqiang94@vip.qq.com (苟志强)
 * @date 2017-8-23 下午5:11:57
 */
public class RedisUtil {
	/**私有构造函数 使类禁止实例化*/
	private RedisUtil(){}
	/**Redis服务器IP*/
	private static final String redis_path = "localhost";
	/**Redis端口号*/
	private static final int redis_port = 6379;
	/**Redis访问密码*/
//	private static final String redis_pwd = "";
	/**连接实例的最大数目*/ //可用连接实例的最大数目，默认值为8；如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
	private static final int max_total = 300;
	/**最大空闲实例*/ //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
	private static final int max_idle = 100;
	/**等待可用连接的最大时间*/ //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException
	private static final int max_wait = 10000;
	/**Redis对象实例关闭时间*/
	private static int out_time = 10000;
	//在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
	private static boolean test_on_borrow = true;
	/**Redis连接池*/
	private static JedisPool jedisPool = null;
	/**初始化Redis连接池*/
	static {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(max_total);
			config.setMaxIdle(max_idle);
			config.setMaxWaitMillis(max_wait);
			config.setTestOnBorrow(test_on_borrow);
			//需要访问密码的
//			jedisPool = new JedisPool(config, redis_path, redis_port, out_time,redis_pwd);
			jedisPool = new JedisPool(config, redis_path, redis_port, out_time);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * @Title: getJedis
	 * @Description: TODO(获取Jedis实例)
	 * @author zhiqiang94@vip.qq.com (苟志强)
	 * @date  2017-8-23 下午4:49:04
	 * @return
	 */
	public synchronized static Jedis getJedis() {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				System.out.println("【Redis/Jedis】获取Jedis实例成功！");
				return resource;
			}
		} catch (Exception e) {
			System.out.println("【Redis/Jedis】"+e.toString());
		}
		System.out.println("【Redis/Jedis】获取Jedis实例失败！");
		return null;
	}
	/**
	 * @Title: returnResource
	 * @Description: TODO(释放jedis)
	 * @author zhiqiang94@vip.qq.com (苟志强)
	 * @date  2017-8-23 下午4:49:11
	 * @param jedis
	 */
	public static void close(final Jedis jedis) {
		jedis.close();
		System.out.println("【Redis/Jedis】释放Jedis。");
	}
	
	public static void main(String[] args) {
		RedisUtil.getJedis().set("a", "abc321");
		RedisUtil.getJedis().set("newname", "中文测试");
		System.out.println(RedisUtil.getJedis().get("a"));
		System.out.println(RedisUtil.getJedis().get("newname"));
		System.out.println(RedisUtil.getJedis().get("mykey"));
	}


}
