package com.fshark.overseas.advert.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisException;

import java.util.function.Function;

/**
 * @author libing
 * @version 1.0
 * @date 2019-08-02 16:06
 */
public class RedisClientUtils {

    private static Logger LOG = LoggerFactory.getLogger(RedisClientUtils.class);

    public static <R> R using(JedisPool jedisPool, int maxRetry, Function<Jedis, R> apply) {
        do {
            try (Jedis client = jedisPool.getResource()) {
                return apply.apply(client);
            } catch (JedisException e) {
                LOG.error("retry " + maxRetry, e);
            }
        } while (--maxRetry >= 0);
        return null;
    }

    public static JedisPoolConfig getGeneralRedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(2);
        jedisPoolConfig.setMaxIdle(2);
        jedisPoolConfig.setTestWhileIdle(true);
        return jedisPoolConfig;
    }
}
