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 java.io.IOException;
012
013import org.nuxeo.ecm.core.redis.retry.ExponentialBackofDelay;
014import org.nuxeo.ecm.core.redis.retry.Retry;
015import org.nuxeo.ecm.core.redis.retry.Retry.ContinueException;
016import org.nuxeo.ecm.core.redis.retry.Retry.FailException;
017
018import redis.clients.jedis.Jedis;
019import redis.clients.jedis.exceptions.JedisConnectionException;
020import redis.clients.util.Pool;
021
022public class RedisFailoverExecutor implements RedisExecutor {
023
024    protected final int timeout;
025
026    protected final RedisExecutor executor;
027
028    public RedisFailoverExecutor(int timeout, RedisExecutor base) {
029        this.timeout = timeout;
030        executor = base;
031    }
032
033    @Override
034    public <T> T execute(final RedisCallable<T> callable) throws JedisConnectionException {
035        try {
036            return new Retry().retry(new Retry.Block<T>() {
037
038                @Override
039                public T retry() throws ContinueException, FailException {
040                    try {
041                        return executor.execute(callable);
042                    } catch (JedisConnectionException cause) {
043                        throw new Retry.ContinueException(cause);
044                    }
045                }
046
047            }, new ExponentialBackofDelay(1, timeout));
048        } catch (FailException cause) {
049            throw new JedisConnectionException("Cannot reconnect to jedis ..", cause);
050        }
051    }
052
053    @Override
054    public Pool<Jedis> getPool() {
055        return executor.getPool();
056    }
057
058    @Override
059    public boolean supportPipelined() {
060        return executor.supportPipelined();
061    }
062
063}