001/*******************************************************************************
002 * Copyright (c) 2006-2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 ******************************************************************************/
009package org.nuxeo.ecm.core.redis;
010
011import redis.clients.jedis.Jedis;
012import redis.clients.jedis.exceptions.JedisConnectionException;
013import redis.clients.jedis.exceptions.JedisException;
014import redis.clients.util.Pool;
015
016public class RedisPoolExecutor implements RedisExecutor {
017
018    protected Pool<Jedis> pool;
019
020    public RedisPoolExecutor(Pool<Jedis> pool) {
021        this.pool = pool;
022    }
023
024    @Override
025    public <T> T execute(RedisCallable<T> callable) throws JedisException {
026        Jedis jedis = pool.getResource();
027        boolean brokenResource = false;
028        try {
029            return callable.call(jedis);
030        } catch (JedisConnectionException cause) {
031            brokenResource = true;
032            throw cause;
033        } finally {
034            if (brokenResource) {
035                pool.returnBrokenResource(jedis);
036            } else {
037                pool.returnResource(jedis);
038            }
039        }
040
041    }
042
043    @Override
044    public Pool<Jedis> getPool() {
045        return pool;
046    }
047
048    @Override
049    public boolean supportPipelined() {
050        return true;
051    }
052
053}