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