package com.dashitech.redis.core;

import com.dashitech.utils.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis抽象工厂实例类，务必在Spring的数据库配置加载完成后在调用此类！否则会报错
 * Created by CX on 2018/8/20 0020.
 */
public abstract class JedisPoolFactory {
    private static JedisPool pool;


    private synchronized static JedisPool getJedisPool() {
        if (pool == null) {
            String host = PropertiesUtil.getProperty("spring.redis.host");
            Integer port = PropertiesUtil.getInteger("spring.redis.port");
            String password = PropertiesUtil.getProperty("spring.redis.password");
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(PropertiesUtil.getInteger("spring.redis.pool.max-total"));
            config.setMaxIdle(PropertiesUtil.getInteger("spring.redis.pool.max-idle"));
            config.setMaxWaitMillis(PropertiesUtil.getInteger("spring.redis.pool.max-wait-millis"));
            config.setTestOnBorrow(true);
            pool = new JedisPool(config, host, port,5000,password);
        }
        return pool;
    }


    private synchronized static JedisPool getDefaultJedisPool() {
        if (pool == null) {
            String host = "127.0.0.1";
            Integer port = 6379;
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(100);
            config.setMaxIdle(20);
            config.setMaxWaitMillis(10000);
            config.setTestOnBorrow(true);
            pool = new JedisPool(config, host, port);
        }
        return pool;
    }

    /**
     * 使用默认127.0.0.1和默认6379端口
     *
     * @return
     */
    public synchronized static Jedis getDefaultJedis() {
        if (pool == null) {
            return getDefaultJedisPool().getResource();
        } else {
            return pool.getResource();
        }
    }


    /**
     * 读数据库userRedisIp和userRedisPort，如果没有读取到报错
     */
    public synchronized static Jedis getJedis() {
        if (pool == null) {
            return getJedisPool().getResource();
        } else {
            return pool.getResource();
        }
    }

}
