首页 > Jedis cluster如何使用连接池?

Jedis cluster如何使用连接池?

现在已经使用Jedis-2.7.2.jar实现了redis 集群的连接和操作,但是单个连接不适用于实际,请问有人做过Jedis cluster的连接池操作吗?我知道用commons-pool.jar但是不知道具体实现细节,网上也一直没有找到,求用过的或者知道的能给个链接或者贴段代码,谢谢!


给你个小 demo,在实际的项目中我也只是使用过一次,还是实习生的时候。

网上可参考的demo比较多,注意版本,高版本的jedis api和低版本的有差别,主要是config那块。

这个代码是使用低版本的实现的。基本都有注释。

/**
 * Created by Nicholas on 2015/10/19.
 */

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class Test {
    private static JedisPool pool = null;
    public static JedisPool getPool() {
        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            /**
             * 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取
             * 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,
             * 则此时pool的状态为exhausted(耗尽)
             */
            config.setMaxActive(500);
            /**
             *  控制一个pool最多有多少个状态为idle(空闲的)的jedis实例
             */
            config.setMaxIdle(5);
            /**
             * 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,
             * 则直接抛出JedisConnectionException
             */
            config.setMaxWait(1000 * 100);
            /**
             * 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,
             * 则得到的jedis实例均是可用的
             */
            config.setTestOnBorrow(true);
            pool = new JedisPool(config, "127.0.0.1", 8888);
        }
        return pool;
    }

    /**
     * 返还到连接池
     *
     * @param pool
     * @param redis
     */
    public static void returnResource(JedisPool pool, Jedis redis) {
        if (redis != null) {
            pool.returnResource(redis);
        }
    }

    /**
     * @brief 获取数据
     * @param key
     * @return
     */
    public static String get(String key){
        String value = null;
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = getPool();
            jedis = pool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
            /**
             * 释放redis对象
             */
            pool.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            /**
             *  返还到连接池
             */
            returnResource(pool, jedis);
        }
        return value;
    }
}

你好,请问你解决了吗,我也是遇到类似的问题,我是想用jedisCluster对象操作redis的事物

【热门文章】
【热门文章】