JedisPool使用实战

JedisPool是jedis客户端连接池,典型使用方式如下:

Jedis jedis = pool.getResource();
        try {
            //操作redis
            jedis.set("key" , "value") ;
        } catch (JedisException e) {
            pool.returnBrokenResource(jedis);
        }finally {
            pool.returnResource(jedis);

        }

这种代码写到写多了真的会吐血,一不小心忘了返还jedis到pool,问题就大了。于是想起spring jdbctemplate 实现方式,所以有了一下使用方式:

RedisTemplate redisTemplate = new RedisTemplate(RedisFactory.getInstance("redis.properties").getJedisPool());

        String value = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String handle(Jedis jedis) {
                return jedis.get("key");
            }
        }) ;

哈哈,再也不用担心出错了,RedisTemplate封装了从JedisPool取jedis以及返回池中代码而已,具体如下:

/**
 * Created by wens on 15-3-19.
 */
public class RedisTemplate {

    private JedisPool jedisPool ;

    public RedisTemplate(JedisPool jedisPool){
        this.jedisPool = jedisPool ;
    }

    public <T> T  execute(RedisCallback<T> callback){

        Jedis jedis = jedisPool.getResource();
        boolean broken = false;
        try {
            return callback.handle( jedis);
        } catch (JedisException e) {
            broken = true;
            throw  new RedisException(e);
        } catch (Exception e) {
            throw  new RedisException(e);
        } finally {
            returnResource(jedis, broken);

        }

    }

    private void returnResource(Jedis jedis, boolean broken) {
        if (jedis != null) {
            if (broken) {
                jedisPool.returnBrokenResource(jedis);
            } else {
                jedisPool.returnResource(jedis);
            }
        }
    }
}

/**
 * Created by wens on 15-3-19.
 */
public interface RedisCallback<T> {
    public T handle(Jedis jedis);
}





你可能感兴趣的:(jedis,jedispool)