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

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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//from  w  w w  .  ja  v  a 2s . 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

protected <V, R> void async(final boolean readOnlyMode, final NodeSource source, final Codec codec,
        final RedisCommand<V> command, final Object[] params, final RPromise<R> mainPromise,
        final int attempt) {
    if (mainPromise.isCancelled()) {
        return;/* w w w.  j a va 2s  . c  o m*/
    }

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

    final AsyncDetails<V, R> details = AsyncDetails.acquire();
    if (isRedissonReferenceSupportEnabled()) {
        try {
            for (int i = 0; i < params.length; i++) {
                RedissonReference reference = redisson != null
                        ? RedissonObjectFactory.toReference(redisson, params[i])
                        : RedissonObjectFactory.toReference(redissonReactive, params[i]);
                params[i] = reference == null ? params[i] : reference;
            }
        } catch (Exception e) {
            connectionManager.getShutdownLatch().release();
            mainPromise.tryFailure(e);
            return;
        }
    }

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

    final RPromise<R> attemptPromise = connectionManager.newPromise();
    details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise,
            attempt);

    final TimerTask retryTimerTask = new TimerTask() {

        @Override
        public void run(Timeout t) throws Exception {
            if (details.getAttemptPromise().isDone()) {
                return;
            }

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

            if (details.getMainPromise().isCancelled()) {
                if (details.getAttemptPromise().cancel(false)) {
                    AsyncDetails.release(details);
                }
                return;
            }

            if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Command execution timeout for command: "
                            + command + " with params: " + LogHelper.toString(details.getParams())));
                }
                details.getAttemptPromise().tryFailure(details.getException());
                return;
            }
            if (!details.getAttemptPromise().cancel(false)) {
                return;
            }

            int count = details.getAttempt() + 1;
            if (log.isDebugEnabled()) {
                log.debug("attempt {} for command {} and params {}", count, details.getCommand(),
                        Arrays.toString(details.getParams()));
            }
            async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(),
                    details.getParams(), details.getMainPromise(), count);
            AsyncDetails.release(details);
        }
    };

    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 {
            if (connFuture.isCancelled()) {
                return;
            }

            if (!connFuture.isSuccess()) {
                connectionManager.getShutdownLatch().release();
                details.setException(convertException(connectionFuture));
                return;
            }

            if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) {
                releaseConnection(source, connectionFuture, details.isReadOnlyMode(),
                        details.getAttemptPromise(), details);
                return;
            }

            final RedisConnection connection = connFuture.getNow();
            if (details.getSource().getRedirect() == Redirect.ASK) {
                List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(2);
                RPromise<Void> promise = connectionManager.newPromise();
                list.add(new CommandData<Void, Void>(promise, details.getCodec(), RedisCommands.ASKING,
                        new Object[] {}));
                list.add(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(),
                        details.getCommand(), details.getParams()));
                RPromise<Void> main = connectionManager.newPromise();
                ChannelFuture future = connection.send(new CommandsData(main, list));
                details.setWriteFuture(future);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("aquired connection for command {} and params {} from slot {} using node {}",
                            details.getCommand(), Arrays.toString(details.getParams()), details.getSource(),
                            connection.getRedisClient().getAddr());
                }
                ChannelFuture future = connection.send(new CommandData<V, R>(details.getAttemptPromise(),
                        details.getCodec(), details.getCommand(), details.getParams()));
                details.setWriteFuture(future);
            }

            details.getWriteFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    checkWriteFuture(details, connection);
                }
            });

            releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(),
                    details);
        }
    });

    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            checkAttemptFuture(source, details, future);
        }
    });
}

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();// www .j ava 2 s  .com
    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  . j a  v  a2 s.  c om*/

    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;/*from w w  w.  ja  v a 2 s . c o  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 va 2s  .  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.j ava2s .  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();/*ww  w  .j  a  v  a  2 s  .c  om*/
    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  ww. j  av a2  s  . co 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;
}

From source file:org.redisson.connection.ClientConnectionsEntry.java

License:Apache License

private <T extends RedisConnection> void addFireEventListener(T conn, RPromise<T> connectionFuture) {
    connectionManager.getConnectListener().onConnect(connectionFuture, conn, nodeType,
            connectionManager.getConfig());

    if (connectionFuture.isSuccess()) {
        connectionManager.getConnectionEventsHub()
                .fireConnect(connectionFuture.getNow().getRedisClient().getAddr());
        return;/*from   www  .j  a va  2  s .  co m*/
    }

    connectionFuture.addListener(new FutureListener<T>() {
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (future.isSuccess()) {
                connectionManager.getConnectionEventsHub()
                        .fireConnect(future.getNow().getRedisClient().getAddr());
            }
        }
    });
}