RedisPool

这里要求Jedis的版本为2.6.0 

import com.mmall.utils.YamlUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
    private static JedisPool jedisPool;
    /**
     * 最大连接数
     *
     * @info 2019-10-21 16:45 liuxi
     * @param null
     */
    private static Integer maxTotal = Integer.valueOf(YamlUtils.getString("redis.max.total"));
    /**
     * 在jedisPool中最小的idle状态的jedis市里的个数
     *
     * @info 2019-10-21 16:45 liuxi
     * @param null
     */
    private static Integer maxIdle = Integer.valueOf(YamlUtils.getString("redis.max.idle"));
    /**
     * 在jedisPool中最小的idle状态的jedis市里的个数
     *
     * @info 2019-10-21 16:45 liuxi
     * @param null
     */
    private static Integer minIdle = Integer.valueOf(YamlUtils.getString("redis.min.idle"));

    /**
     * 在borrow一个Jedis连接的时候是否要验证,验证过后的连接肯定是可以正常使用的
     *
     * @info 2019-10-21 16:45 liuxi
     * @param null
     */
    private static Boolean testOnBorrow = Boolean.valueOf(YamlUtils.getString("redis.test.borrow"));
    /**
     * 在Return一个Jedis连接的时候是否要验证,验证过后的连接肯定是可以正常使用的
     *
     * @info 2019-10-21 16:46 liuxi
     * @param null
     */
    private static Boolean testOnReturn = Boolean.valueOf(YamlUtils.getString("redis.test.return"));

    private static String redisIp = YamlUtils.getString("redis.ip");
    private static Integer redisPort = Integer.parseInt(YamlUtils.getString("redis.port"));

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        /**
         *       连接耗尽的时候,是否阻塞,false会抛出异常,true阻塞直到超时。默认为true。
         * @info 2019-10-21 17:09 liuxi
         *        
         */
        config.setBlockWhenExhausted(true);

        jedisPool = new JedisPool(config, redisIp, redisPort, 1000 * 2);
    }

    static {
        initPool();
    }

    public static Jedis getJedis() {
        return jedisPool.getResource();
    }


    public static void returnBrokenResource(Jedis jedis) {
        jedisPool.returnBrokenResource(jedis);
    }


    public static void returnResource(Jedis jedis) {
        jedisPool.returnResource(jedis);
    }


    public static void main(String[] args) {
        Jedis jedis = jedisPool.getResource();
        jedis.set("geelykey", "geelyvalue");
        returnResource(jedis);

        jedisPool.destroy();//临时调用,销毁连接池中的所有连接
        System.out.println("program is end");


    }
}

 

posted on 2019-10-21 17:11  刘相如  阅读(803)  评论(0)    收藏  举报