package com.iamberry.redis;

import com.alibaba.fastjson.JSONObject;
import com.iamberry.wechat.tools.NameUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

/**
 * redis工具类
 * @author root
 */
public class RedisUtils {

    /**ip*/
    private static final String IP = NameUtils.getConfig("redis_host");
    /**端口*/
    private static final int PORT = Integer.parseInt(NameUtils.getConfig("redis_port"));
    /**密码(原始默认是没有密码)*/
    private static final String AUTH = NameUtils.getConfig("redis_auth");
    /**最大连接数*/
    private static int   MAX_ACTIVE = Integer.parseInt(NameUtils.getConfig("redis_max_active"));
    /**设置最大空闲数*/
    private static int   MAX_IDLE = Integer.parseInt(NameUtils.getConfig("redis_max_idle"));
    /**最大连接时间*/
    private static int   MAX_WAIT = Integer.parseInt(NameUtils.getConfig("redis_max_wait"));
    /**超时时间*/
    private static int   TIMEOUT = Integer.parseInt(NameUtils.getConfig("redis_timeout"));

    private static JedisPool pool = null;

    private static Logger logger = Logger.getLogger(RedisUtils.class);

    static {
        /*
         * 初始化线程池(只在类进行初始化的时候进行一次)
         */
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(MAX_ACTIVE);
        config.setMaxIdle(MAX_IDLE);
        config.setMaxWaitMillis(MAX_WAIT);
        config.setTestOnBorrow(false);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        pool = new JedisPool(config, IP, PORT, TIMEOUT);
    }

    /**
     * 获取连接
     */
    private static synchronized Jedis getJedis() {
        try {
            if(pool != null) {
                Jedis jedis = pool.getResource();
                jedis.auth(AUTH);
                return jedis;
            } else {
                throw new RuntimeException("获取失败Redis实例失败，请重试");
            }
        } catch (Exception e) {
            logger.error("", e);
            throw e;
        }
    }

    /**
     * 插入对象
     * @param key
     * @param obj
     * @return
     */
    public static boolean put(String key, Object obj) {
        Jedis jedis = null;
        try {
            String value = JSONObject.toJSONString(obj);
            jedis = getJedis();
            return "ok".equalsIgnoreCase(jedis.set(key, value));
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return false;
    }

    /**
     * 插入对象
     * @param key
     * @param value
     * @return
     */
    public static boolean put(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return "ok".equalsIgnoreCase(jedis.set(key, value));
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return false;
    }

    /**
     * 获取单个对象
     * @param key
     * @param clazz
     * @return
     */
    public static <T> T get(String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            String result = jedis.get(key);
            return JSONObject.parseObject(result, clazz);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return null;
    }

    /**
     * 获取单个String对象
     * @param key
     * @return
     */
    public static String get(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return null;
    }

    /**
     * 获取list集合
     * @param key
     * @param clazz
     * @return
     */
    public static <T> List<T> list(String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            String result = jedis.get(key);
            return JSONObject.parseArray(result, clazz);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return null;
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public static boolean del(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.del(key) >= 1;
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            getColse(jedis);
        }
        return false;
    }

    /**
     * 关闭连接
     * @param jedis
     */
    private static void getColse(Jedis jedis) {
        if(jedis != null) {
            jedis.close();
        }
    }
}