package com.sifang.modules.config;

import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@Component
public class SfJedisPool {

    public static SfJedisPool instance = new SfJedisPool();
    private static final Map<Integer, JedisPool> poolMap = new HashMap<>();

    private SfJedisPool() {
    }

    JedisPool getPool(SfJedisPoolParameterConfig sfJedisPoolParameterConfig) {
        int db = sfJedisPoolParameterConfig.getDatabase();
        if (poolMap.get(db) == null || poolMap.get(db).isClosed()) {
            synchronized (poolMap) {
                if (poolMap.get(db) == null || poolMap.get(db).isClosed()) {
                    RedisProperties redisProperties = new RedisProperties();
                    redisProperties.setHost(sfJedisPoolParameterConfig.getHost());
                    redisProperties.setPassword(sfJedisPoolParameterConfig.getPassword());
                    redisProperties.setPort(sfJedisPoolParameterConfig.getPort());
                    redisProperties.setDatabase(sfJedisPoolParameterConfig.getDatabase());
                    redisProperties.setMaxTotal(1000);

                    JedisPool pool = new JedisPool(redisProperties, redisProperties.getHost(),
                            redisProperties.getPort(), redisProperties.getConnectionTimeout(),
                            redisProperties.getSoTimeout(), redisProperties.getPassword(),
                            redisProperties.getDatabase(), redisProperties.getClientName(),
                            redisProperties.isSsl(), redisProperties.getSslSocketFactory(),
                            redisProperties.getSslParameters(), redisProperties.getHostnameVerifier());

                    poolMap.put(db, pool);
                }
            }
        }
        return poolMap.get(db);
    }

    /**
     * 回收Jedis对象资源
     */
    public void close(JedisPool pool) {
        pool.close();
    }
}
