Example usage for io.netty.util.concurrent Future cause

List of usage examples for io.netty.util.concurrent Future cause

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

private <T, R> RFuture<R> allAsync(boolean readOnlyMode, RedisCommand<T> command,
        final SlotCallback<T, R> callback, Object... params) {
    final RPromise<R> mainPromise = connectionManager.newPromise();
    final Set<MasterSlaveEntry> nodes = connectionManager.getEntrySet();
    final AtomicInteger counter = new AtomicInteger(nodes.size());
    FutureListener<T> listener = new FutureListener<T>() {
        @Override/*from   ww  w  .  j ava  2s .co  m*/
        public void operationComplete(Future<T> future) throws Exception {
            if (!future.isSuccess()) {
                mainPromise.tryFailure(future.cause());
                return;
            }

            if (callback != null) {
                callback.onSlotResult(future.getNow());
            }
            if (counter.decrementAndGet() == 0) {
                if (callback != null) {
                    mainPromise.trySuccess(callback.onFinish());
                } else {
                    mainPromise.trySuccess(null);
                }
            }
        }
    };

    for (MasterSlaveEntry entry : nodes) {
        RPromise<T> promise = connectionManager.newPromise();
        promise.addListener(listener);
        async(readOnlyMode, new NodeSource(entry), connectionManager.getCodec(), command, params, promise, 0);
    }
    return mainPromise;
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

public <T, R> RFuture<R> evalAllAsync(boolean readOnlyMode, RedisCommand<T> command,
        final SlotCallback<T, R> callback, String script, List<Object> keys, Object... params) {
    final RPromise<R> mainPromise = connectionManager.newPromise();
    final Set<MasterSlaveEntry> entries = connectionManager.getEntrySet();
    final AtomicInteger counter = new AtomicInteger(entries.size());
    FutureListener<T> listener = new FutureListener<T>() {

        @Override/*  w  ww.j  a  v  a  2 s. c o m*/
        public void operationComplete(Future<T> future) throws Exception {
            if (!future.isSuccess()) {
                mainPromise.tryFailure(future.cause());
                return;
            }

            callback.onSlotResult(future.getNow());
            if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                mainPromise.trySuccess(callback.onFinish());
            }
        }
    };

    List<Object> args = new ArrayList<Object>(2 + keys.size() + params.length);
    args.add(script);
    args.add(keys.size());
    args.addAll(keys);
    args.addAll(Arrays.asList(params));
    for (MasterSlaveEntry entry : entries) {
        RPromise<T> promise = connectionManager.newPromise();
        promise.addListener(listener);
        async(readOnlyMode, new NodeSource(entry), connectionManager.getCodec(), command, args.toArray(),
                promise, 0);
    }
    return mainPromise;
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

private <R, V> void handleBlockingOperations(final AsyncDetails<V, R> details, final RedisConnection connection,
        Long popTimeout) {/* w w  w  .ja  v a  2 s  . c om*/
    final FutureListener<Boolean> listener = new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            details.getMainPromise().tryFailure(new RedissonShutdownException("Redisson is shutdown"));
        }
    };

    final AtomicBoolean canceledByScheduler = new AtomicBoolean();
    final Timeout scheduledFuture;
    if (popTimeout != 0) {
        // to handle cases when connection has been lost
        final Channel orignalChannel = connection.getChannel();
        scheduledFuture = connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                // re-connection wasn't made
                // and connection is still active
                if (orignalChannel == connection.getChannel() && connection.isActive()) {
                    return;
                }

                canceledByScheduler.set(true);
                details.getAttemptPromise().trySuccess(null);
            }
        }, popTimeout, TimeUnit.SECONDS);
    } else {
        scheduledFuture = null;
    }

    details.getMainPromise().addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (scheduledFuture != null) {
                scheduledFuture.cancel();
            }

            synchronized (listener) {
                connectionManager.getShutdownPromise().removeListener(listener);
            }

            // handling cancel operation for commands from skipTimeout collection
            if ((future.isCancelled() && details.getAttemptPromise().cancel(true))
                    || canceledByScheduler.get()) {
                connection.forceFastReconnectAsync();
                return;
            }

            if (future.cause() instanceof RedissonShutdownException) {
                details.getAttemptPromise().tryFailure(future.cause());
            }
        }
    });

    synchronized (listener) {
        if (!details.getMainPromise().isDone()) {
            connectionManager.getShutdownPromise().addListener(listener);
        }
    }
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

private <R, V> void checkAttemptFuture(final NodeSource source, final AsyncDetails<V, R> details,
        Future<R> future) {
    details.getTimeout().cancel();//from   w w  w . ja  v  a2s  . c  o  m
    if (future.isCancelled()) {
        return;
    }

    if (future.cause() instanceof RedisMovedException) {
        RedisMovedException ex = (RedisMovedException) future.cause();
        async(details.isReadOnlyMode(), new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.MOVED),
                details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(),
                details.getAttempt());
        AsyncDetails.release(details);
        return;
    }

    if (future.cause() instanceof RedisAskException) {
        RedisAskException ex = (RedisAskException) future.cause();
        async(details.isReadOnlyMode(), new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.ASK),
                details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(),
                details.getAttempt());
        AsyncDetails.release(details);
        return;
    }

    if (future.cause() instanceof RedisLoadingException) {
        async(details.isReadOnlyMode(), source, details.getCodec(), details.getCommand(), details.getParams(),
                details.getMainPromise(), details.getAttempt());
        AsyncDetails.release(details);
        return;
    }

    if (future.cause() instanceof RedisTryAgainException) {
        connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                async(details.isReadOnlyMode(), source, details.getCodec(), details.getCommand(),
                        details.getParams(), details.getMainPromise(), details.getAttempt());

            }
        }, 1, TimeUnit.SECONDS);
        AsyncDetails.release(details);
        return;
    }

    if (future.isSuccess()) {
        R res = future.getNow();
        if (res instanceof RedisClientResult) {
            InetSocketAddress addr = source.getAddr();
            if (addr == null) {
                addr = details.getConnectionFuture().getNow().getRedisClient().getAddr();
            }
            ((RedisClientResult) res).setRedisClient(addr);
        }

        if (isRedissonReferenceSupportEnabled()) {
            handleReference(details.getMainPromise(), res);
        } else {
            details.getMainPromise().trySuccess(res);
        }
    } else {
        details.getMainPromise().tryFailure(future.cause());
    }
    AsyncDetails.release(details);
}

From source file:org.redisson.command.CommandBatchService.java

License:Apache License

public RFuture<List<?>> executeAsync() {
    if (executed) {
        throw new IllegalStateException("Batch already executed!");
    }/*from w w w. ja va2  s  .com*/

    if (commands.isEmpty()) {
        return connectionManager.newSucceededFuture(null);
    }
    executed = true;

    RPromise<Void> voidPromise = connectionManager.newPromise();
    final RPromise<List<?>> promise = connectionManager.newPromise();
    voidPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
                commands = null;
                return;
            }

            List<BatchCommandData> entries = new ArrayList<BatchCommandData>();
            for (Entry e : commands.values()) {
                entries.addAll(e.getCommands());
            }
            Collections.sort(entries);
            List<Object> result = new ArrayList<Object>(entries.size());
            for (BatchCommandData<?, ?> commandEntry : entries) {
                Object entryResult = commandEntry.getPromise().getNow();
                if (isRedissonReferenceSupportEnabled() && entryResult instanceof RedissonReference) {
                    result.add(redisson != null
                            ? RedissonObjectFactory.<Object>fromReference(redisson,
                                    (RedissonReference) entryResult)
                            : RedissonObjectFactory.<Object>fromReference(redissonReactive,
                                    (RedissonReference) entryResult));
                } else {
                    result.add(entryResult);
                }
            }
            promise.trySuccess(result);
            commands = null;
        }
    });

    AtomicInteger slots = new AtomicInteger(commands.size());
    for (java.util.Map.Entry<MasterSlaveEntry, Entry> e : commands.entrySet()) {
        execute(e.getValue(), new NodeSource(e.getKey()), voidPromise, slots, 0, false);
    }
    return promise;
}

From source file:org.redisson.command.CommandBatchService.java

License:Apache License

private void execute(final Entry entry, final NodeSource source, final RPromise<Void> mainPromise,
        final AtomicInteger slots, final int attempt, final boolean noResult) {
    if (mainPromise.isCancelled()) {
        return;//w w w  . jav a  2 s . co m
    }

    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.tryFailure(new IllegalStateException("Redisson is shutdown"));
        return;
    }

    final RPromise<Void> attemptPromise = connectionManager.newPromise();

    final AsyncDetails details = new AsyncDetails();

    final RFuture<RedisConnection> connectionFuture;
    if (entry.isReadOnlyMode()) {
        connectionFuture = connectionManager.connectionReadOp(source, null);
    } else {
        connectionFuture = connectionManager.connectionWriteOp(source, null);
    }

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }

            if (connectionFuture.cancel(false)) {
                connectionManager.getShutdownLatch().release();
            } else {
                if (connectionFuture.isSuccess()) {
                    ChannelFuture writeFuture = details.getWriteFuture();
                    if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
                        return;
                    }
                }
            }

            if (mainPromise.isCancelled()) {
                attemptPromise.cancel(false);
                return;
            }

            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Batch command execution timeout"));
                }
                attemptPromise.tryFailure(details.getException());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }

            int count = attempt + 1;
            execute(entry, source, mainPromise, slots, count, noResult);
        }
    };

    Timeout timeout = connectionManager.newTimeout(retryTimerTask,
            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);

    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
            checkConnectionFuture(entry, source, mainPromise, attemptPromise, details, connectionFuture,
                    noResult);
        }
    });

    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            details.getTimeout().cancel();
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.MOVED), mainPromise, slots,
                        attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisAskException) {
                RedisAskException ex = (RedisAskException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.ASK), mainPromise, slots,
                        attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisLoadingException) {
                entry.clearErrors();
                execute(entry, source, mainPromise, slots, attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisTryAgainException) {
                entry.clearErrors();
                connectionManager.newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) throws Exception {
                        execute(entry, source, mainPromise, slots, attempt, noResult);
                    }
                }, 1, TimeUnit.SECONDS);
                return;
            }

            if (future.isSuccess()) {
                if (slots.decrementAndGet() == 0) {
                    mainPromise.trySuccess(future.getNow());
                }
            } else {
                mainPromise.tryFailure(future.cause());
            }
        }
    });
}

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public Future<List<?>> executeAsync() {
    if (executed) {
        throw new IllegalStateException("Batch already executed!");
    }/*from w w  w.  j  a v a 2  s .  c o m*/

    if (commands.isEmpty()) {
        return connectionManager.getGroup().next().newSucceededFuture(null);
    }
    executed = true;

    Promise<Void> voidPromise = connectionManager.newPromise();
    final Promise<List<?>> promise = connectionManager.newPromise();
    voidPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                promise.setFailure(future.cause());
                return;
            }

            List<CommandEntry> entries = new ArrayList<CommandEntry>();
            for (Entry e : commands.values()) {
                entries.addAll(e.getCommands());
            }
            Collections.sort(entries);
            List<Object> result = new ArrayList<Object>();
            for (CommandEntry commandEntry : entries) {
                result.add(commandEntry.getCommand().getPromise().getNow());
            }
            promise.setSuccess(result);
            commands = null;
        }
    });
    for (java.util.Map.Entry<Integer, Entry> e : commands.entrySet()) {
        execute(e.getValue(), e.getKey(), voidPromise, new AtomicInteger(commands.size()), 0);
    }
    return promise;
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final Promise<R> mainPromise,
        final List<Integer> slots, final Object... params) {
    final Promise<R> attemptPromise = connectionManager.newPromise();
    attemptPromise.addListener(new FutureListener<R>() {
        @Override//from w  w  w  .ja  v  a2s. c o m
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isSuccess()) {
                if (future.getNow() == null) {
                    if (slots.isEmpty()) {
                        mainPromise.setSuccess(null);
                    } else {
                        retryReadRandomAsync(command, mainPromise, slots, params);
                    }
                } else {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });

    Integer slot = slots.remove(0);
    async(true, slot, null, connectionManager.getCodec(), command, params, attemptPromise, 0);
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

public <V> V get(Future<V> future) {
    future.awaitUninterruptibly();/*w  ww  . j ava2 s  . co m*/
    if (future.isSuccess()) {
        return future.getNow();
    }
    throw future.cause() instanceof RedisException ? (RedisException) future.cause()
            : new RedisException("Unexpected exception while processing command", future.cause());
}

From source file:org.redisson.connection.balancer.LoadBalancerManager.java

License:Apache License

public RFuture<Void> add(final ClientConnectionsEntry entry) {
    final RPromise<Void> result = connectionManager.newPromise();
    FutureListener<Void> listener = new FutureListener<Void>() {
        AtomicInteger counter = new AtomicInteger(2);

        @Override//from   w w  w . j a  va2s . c  o m
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            if (counter.decrementAndGet() == 0) {
                addr2Entry.put(entry.getClient().getAddr(), entry);
                result.trySuccess(null);
            }
        }
    };

    RFuture<Void> slaveFuture = slaveConnectionPool.add(entry);
    slaveFuture.addListener(listener);
    RFuture<Void> pubSubFuture = pubSubConnectionPool.add(entry);
    pubSubFuture.addListener(listener);
    return result;
}