package com.jianshui.common.utils;

import com.jianshui.common.utils.spring.SpringUtils;
import org.springframework.core.env.Environment;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Objects;

public class RedisUtil {

    // private static String ADDR = "192.168.18.221";
    private static String ADDR;

    public static int del_time = 36000;
    public static int del_time_company = 1800;

    // private static int PORT = 6379;
    private static int PORT;

    // private static String AUTH = "Aino202163#.";
    private static String AUTH;

    private static int TIMEOUT = 10000;

    private static JedisPool jedisPool = null;

    static {
        try {
            Environment environment = SpringUtils.getBean(Environment.class);
            ADDR = environment.getProperty("spring.redis.host");
            PORT = Integer.parseInt(environment.getProperty("spring.redis.port"));
            AUTH = environment.getProperty("spring.redis.password");
            if (Objects.equals(AUTH, "")) {
                AUTH = null;
            }

            JedisPoolConfig config = new JedisPoolConfig();

            config.setBlockWhenExhausted(true);

            config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");

            config.setJmxEnabled(true);

            config.setJmxNamePrefix("pool");

            config.setLifo(true);

            config.setMaxIdle(8);

            config.setMaxTotal(300);

            config.setMaxWaitMillis(-1L);

            config.setMinEvictableIdleTimeMillis(1800000L);

            config.setMinIdle(0);

            config.setNumTestsPerEvictionRun(3);

            config.setSoftMinEvictableIdleTimeMillis(1800000L);

            config.setTestOnBorrow(true);

            config.setTestWhileIdle(true);

            config.setTimeBetweenEvictionRunsMillis(30000L);

            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Jedis jedis) {
        if (jedis != null)
            jedis.close();
    }
}
