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

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

Introduction

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

Prototype

V getNow();

Source Link

Document

Return the result without blocking.

Usage

From source file:org.redisson.BaseRemoteService.java

License:Apache License

private RFuture<RemoteServiceAck> tryPollAckAgainAsync(RemoteInvocationOptions optionsCopy,
        final RBlockingQueue<RemoteServiceAck> responseQueue, String ackName) throws InterruptedException {
    final RPromise<RemoteServiceAck> promise = commandExecutor.getConnectionManager().newPromise();
    RFuture<Boolean> ackClientsFuture = commandExecutor.evalWriteAsync(ackName, LongCodec.INSTANCE,
            RedisCommands.EVAL_BOOLEAN,/*from w w  w.  j a  v  a2  s  .  c  om*/
            "if redis.call('setnx', KEYS[1], 1) == 1 then " + "redis.call('pexpire', KEYS[1], ARGV[1]);"
                    + "return 0;" + "end;" + "redis.call('del', KEYS[1]);" + "return 1;",
            Arrays.<Object>asList(ackName), optionsCopy.getAckTimeoutInMillis());
    ackClientsFuture.addListener(new FutureListener<Boolean>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
                return;
            }

            if (future.getNow()) {
                RFuture<RemoteServiceAck> pollFuture = responseQueue.pollAsync();
                pollFuture.addListener(new FutureListener<RemoteServiceAck>() {
                    @Override
                    public void operationComplete(Future<RemoteServiceAck> future) throws Exception {
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        promise.trySuccess(future.getNow());
                    }
                });
            } else {
                promise.trySuccess(null);
            }
        }
    });
    return promise;
}

From source file:org.redisson.cluster.ClusterConnectionManager.java

License:Apache License

private RFuture<Collection<RFuture<Void>>> addMasterEntry(final ClusterPartition partition,
        final ClusterServersConfig cfg) {
    if (partition.isMasterFail()) {
        RedisException e = new RedisException("Failed to add master: " + partition.getMasterAddress()
                + " for slot ranges: " + partition.getSlotRanges() + ". Reason - server has FAIL flag");

        if (partition.getSlotRanges().isEmpty()) {
            e = new RedisException("Failed to add master: " + partition.getMasterAddress()
                    + ". Reason - server has FAIL flag");
        }//from   w w  w. j a  v  a  2 s  .  c o  m
        return newFailedFuture(e);
    }

    final RPromise<Collection<RFuture<Void>>> result = newPromise();
    RFuture<RedisConnection> connectionFuture = connect(cfg, partition.getMasterAddress());
    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                log.error("Can't connect to master: {} with slot ranges: {}", partition.getMasterAddress(),
                        partition.getSlotRanges());
                result.tryFailure(future.cause());
                return;
            }

            final RedisConnection connection = future.getNow();
            RFuture<Map<String, String>> clusterFuture = connection.async(RedisCommands.CLUSTER_INFO);
            clusterFuture.addListener(new FutureListener<Map<String, String>>() {

                @Override
                public void operationComplete(Future<Map<String, String>> future) throws Exception {
                    if (!future.isSuccess()) {
                        log.error("Can't execute CLUSTER_INFO for " + connection.getRedisClient().getAddr(),
                                future.cause());
                        result.tryFailure(future.cause());
                        return;
                    }

                    Map<String, String> params = future.getNow();
                    if ("fail".equals(params.get("cluster_state"))) {
                        RedisException e = new RedisException(
                                "Failed to add master: " + partition.getMasterAddress() + " for slot ranges: "
                                        + partition.getSlotRanges() + ". Reason - cluster_state:fail");
                        log.error("cluster_state:fail for " + connection.getRedisClient().getAddr());
                        result.tryFailure(e);
                        return;
                    }

                    MasterSlaveServersConfig config = create(cfg);
                    config.setMasterAddress(partition.getMasterAddress());

                    final MasterSlaveEntry e;
                    List<RFuture<Void>> futures = new ArrayList<RFuture<Void>>();
                    if (config.getReadMode() == ReadMode.MASTER) {
                        e = new SingleEntry(partition.getSlotRanges(), ClusterConnectionManager.this, config);
                    } else {
                        config.setSlaveAddresses(partition.getSlaveAddresses());

                        e = new MasterSlaveEntry(partition.getSlotRanges(), ClusterConnectionManager.this,
                                config);

                        List<RFuture<Void>> fs = e.initSlaveBalancer(partition.getFailedSlaveAddresses());
                        futures.addAll(fs);
                        if (!partition.getSlaveAddresses().isEmpty()) {
                            log.info("slaves: {} added for slot ranges: {}", partition.getSlaveAddresses(),
                                    partition.getSlotRanges());
                            if (!partition.getFailedSlaveAddresses().isEmpty()) {
                                log.warn("slaves: {} is down for slot ranges: {}",
                                        partition.getFailedSlaveAddresses(), partition.getSlotRanges());
                            }
                        }
                    }

                    RFuture<Void> f = e.setupMasterEntry(config.getMasterAddress().getHost(),
                            config.getMasterAddress().getPort());
                    final RPromise<Void> initFuture = newPromise();
                    futures.add(initFuture);
                    f.addListener(new FutureListener<Void>() {
                        @Override
                        public void operationComplete(Future<Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                log.error("Can't add master: {} for slot ranges: {}",
                                        partition.getMasterAddress(), partition.getSlotRanges());
                                initFuture.tryFailure(future.cause());
                                return;
                            }
                            for (Integer slot : partition.getSlots()) {
                                addEntry(slot, e);
                                lastPartitions.put(slot, partition);
                            }

                            log.info("master: {} added for slot ranges: {}", partition.getMasterAddress(),
                                    partition.getSlotRanges());
                            if (!initFuture.trySuccess(null)) {
                                throw new IllegalStateException();
                            }
                        }
                    });
                    if (!result.trySuccess(futures)) {
                        throw new IllegalStateException();
                    }
                }
            });

        }
    });

    return result;
}

From source file:org.redisson.cluster.ClusterConnectionManager.java

License:Apache License

private void checkClusterState(final ClusterServersConfig cfg, final Iterator<URL> iterator,
        final AtomicReference<Throwable> lastException) {
    if (!iterator.hasNext()) {
        log.error("Can't update cluster state", lastException.get());
        scheduleClusterChangeCheck(cfg, null);
        return;//from  w w  w.j  a  v a  2 s. com
    }
    if (!getShutdownLatch().acquire()) {
        return;
    }
    final URL uri = iterator.next();
    RFuture<RedisConnection> connectionFuture = connect(cfg, uri);
    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                lastException.set(future.cause());
                getShutdownLatch().release();
                checkClusterState(cfg, iterator, lastException);
                return;
            }

            RedisConnection connection = future.getNow();
            updateClusterState(cfg, connection, iterator, uri);
        }
    });
}

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

License:Apache License

@Override
public <T, R> RFuture<Collection<R>> readAllAsync(RedisCommand<T> command, Object... params) {
    final RPromise<Collection<R>> mainPromise = connectionManager.newPromise();
    final Set<MasterSlaveEntry> nodes = connectionManager.getEntrySet();
    final List<R> results = new ArrayList<R>();
    final AtomicInteger counter = new AtomicInteger(nodes.size());
    FutureListener<R> listener = new FutureListener<R>() {
        @Override//from w  ww.  jav a  2  s  . c  om
        public void operationComplete(Future<R> future) throws Exception {
            if (!future.isSuccess()) {
                mainPromise.tryFailure(future.cause());
                return;
            }

            R result = future.getNow();
            if (result instanceof Collection) {
                synchronized (results) {
                    results.addAll((Collection) result);
                }
            } else {
                synchronized (results) {
                    results.add(result);
                }
            }

            if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                mainPromise.trySuccess(results);
            }
        }
    };

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

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

License:Apache License

private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final RPromise<R> mainPromise,
        final List<MasterSlaveEntry> nodes, final Object... params) {
    final RPromise<R> attemptPromise = connectionManager.newPromise();
    attemptPromise.addListener(new FutureListener<R>() {
        @Override// w  w  w .j  a va2  s  . co m
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isSuccess()) {
                if (future.getNow() == null) {
                    if (nodes.isEmpty()) {
                        mainPromise.trySuccess(null);
                    } else {
                        retryReadRandomAsync(command, mainPromise, nodes, params);
                    }
                } else {
                    mainPromise.trySuccess(future.getNow());
                }
            } else {
                mainPromise.tryFailure(future.cause());
            }
        }
    });

    MasterSlaveEntry entry = nodes.remove(0);
    async(true, new NodeSource(entry), connectionManager.getCodec(), command, params, attemptPromise, 0);
}

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  ava2  s  .  com*/
        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//from  ww  w . j  a va 2s.  com
        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;//ww w. j  a v  a2  s .  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();//  w w  w .  ja va  2s . 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

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 ww.  j  ava  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());
            }
        }
    });
}