package com.bailuntec.utils;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
public class RedisUtils {

    private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("redis");
    private static JedisPool jedisPool = null;

    /*
    *  初始化连接池
     */
    static{
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(propertiesUtil.getPropertyAsInt("SETMAXTOTAL"));
        config.setMaxIdle(propertiesUtil.getPropertyAsInt("SETMAXIDLE"));
        config.setMaxWaitMillis(propertiesUtil.getPropertyAsInt("SETMAXWAITMILLLIS"));
        config.setTestOnBorrow(true);
        jedisPool = new JedisPool(config, propertiesUtil.getPropertyAsString("REDIS_URL"), propertiesUtil.getPropertyAsInt("REDIS_PORT"));
        //log.warn("初始化连接池");
    }

    /*
    *  获取redis实例
     */
    public synchronized static Jedis getJedis() {
        Jedis jedis = null;
        try{
            jedis =jedisPool.getResource();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return jedis;
    }

    /*
    *  回收redis对象资源
     */
    public synchronized static void returnResource(Jedis jedis) {
        if(jedis != null) {
            try{
                jedis.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /*
    *  获取key值
     */
    public String getValueByKey(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /*
    *  删除key
     */
    public void deleteByKey(String key) throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.del(key);
        } catch (Exception e) {
            throw e;
        } finally {
            returnResource(jedis);
        }
    }

    /*
    *  设置过期时间值
     */
    public void saveValueByKey(String key, String value) throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(key, value);
            jedis.expire(key, propertiesUtil.getPropertyAsInt("EXPIRETIME"));
        } catch (Exception e) {
            throw e;
        } finally {
            returnResource(jedis);
        }
    }
}
