Example usage for io.netty.util.concurrent Promise cancel

List of usage examples for io.netty.util.concurrent Promise cancel

Introduction

In this page you can find the example usage for io.netty.util.concurrent Promise cancel.

Prototype

@Override
boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

If the cancellation was successful it will fail the future with a CancellationException .

Usage

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise,
        final AtomicInteger slots, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/*from   ww  w .j  av  a  2s.  c o m*/
    }

    final Promise<Void> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            attemptPromise.cancel(true);

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

    try {
        org.redisson.client.RedisConnection connection;
        if (entry.isReadOnlyMode()) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }

        ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size());
        for (CommandEntry c : entry.getCommands()) {
            list.add(c.getCommand());
        }
        ChannelFuture future = connection.send(new CommandsData(attemptPromise, list));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed"));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (entry.isReadOnlyMode()) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                execute(entry, ex.getSlot(), mainPromise, slots, attempt);
                return;
            }

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

From source file:org.redisson.CommandExecutorService.java

License:Apache License

protected <V, R> void async(final boolean readOnlyMode, final int slot,
        final MultiDecoder<Object> messageDecoder, final Codec codec, final RedisCommand<V> command,
        final Object[] params, final Promise<R> mainPromise, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/*from  ww  w  .  ja v  a  2s.c o m*/
    }

    final Promise<R> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }

            int count = attempt + 1;
            async(readOnlyMode, slot, messageDecoder, codec, command, params, mainPromise, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (readOnlyMode) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }
        log.debug("getting connection for command {} via slot {} using {}", command, slot,
                connection.getRedisClient().getAddr());
        ChannelFuture future = connection
                .send(new CommandData<V, R>(attemptPromise, messageDecoder, codec, command, params));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("Can't send command: " + command + ", params: "
                            + params + ", channel: " + future.channel(), future.cause()));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (readOnlyMode) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }
            // TODO cancel timeout

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                connectionManager.getTimer().newTimeout(retryTimerTask,
                        connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                async(readOnlyMode, ex.getSlot(), messageDecoder, codec, command, params, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                mainPromise.setSuccess(future.getNow());
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

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

License:Apache License

private <V, T> void writeAllAsync(final int slot, final AsyncOperation<V, T> asyncOperation,
        final AtomicInteger counter, final Promise<T> mainPromise, final int attempt) {
    final Promise<T> promise = getGroup().next().newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    TimerTask timerTask = new TimerTask() {
        @Override/* ww  w .  j  a  v a  2 s. co m*/
        public void run(Timeout timeout) throws Exception {
            if (promise.isDone()) {
                return;
            }
            if (attempt == config.getRetryAttempts()) {
                promise.setFailure(ex.get());
                return;
            }
            promise.cancel(true);

            int count = attempt + 1;
            writeAllAsync(slot, asyncOperation, counter, mainPromise, count);
        }
    };

    try {
        RedisConnection<Object, V> connection = connectionWriteOp(slot);
        RedisAsyncConnection<Object, V> async = connection.getAsync();
        asyncOperation.execute(promise, async);

        ex.set(new RedisTimeoutException());
        Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS);
        promise.addListener(createReleaseWriteListener(slot, connection, timeout));
    } catch (RedisConnectionException e) {
        ex.set(e);
        timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    promise.addListener(new FutureListener<T>() {
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                writeAllAsync(ex.getSlot(), asyncOperation, counter, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

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

License:Apache License

private <V, T> void writeAsync(final int slot, final AsyncOperation<V, T> asyncOperation,
        final Promise<T> mainPromise, final int attempt) {
    final Promise<T> promise = getGroup().next().newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    TimerTask timerTask = new TimerTask() {
        @Override/*from w  w w .  ja  v a  2  s. co  m*/
        public void run(Timeout timeout) throws Exception {
            if (promise.isDone()) {
                return;
            }
            if (attempt == config.getRetryAttempts()) {
                promise.setFailure(ex.get());
                return;
            }
            promise.cancel(true);

            int count = attempt + 1;
            writeAsync(slot, asyncOperation, mainPromise, count);
        }
    };

    try {
        RedisConnection<Object, V> connection = connectionWriteOp(slot);
        RedisAsyncConnection<Object, V> async = connection.getAsync();
        log.debug("writeAsync for slot {} using {}", slot, connection.getRedisClient().getAddr());
        asyncOperation.execute(promise, async);

        ex.set(new RedisTimeoutException());
        Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS);
        promise.addListener(createReleaseWriteListener(slot, connection, timeout));
    } catch (RedisConnectionException e) {
        ex.set(e);
        timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    promise.addListener(new FutureListener<T>() {
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                writeAsync(ex.getSlot(), asyncOperation, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                mainPromise.setSuccess(future.getNow());
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

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

License:Apache License

private <V, T> void readAsync(final int slot, final AsyncOperation<V, T> asyncOperation,
        final Promise<T> mainPromise, final int attempt) {
    final Promise<T> promise = getGroup().next().newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    TimerTask timerTask = new TimerTask() {
        @Override/*from   w  w  w  .  ja  va 2  s  . c  o m*/
        public void run(Timeout timeout) throws Exception {
            if (promise.isDone()) {
                return;
            }
            if (attempt == config.getRetryAttempts()) {
                promise.setFailure(ex.get());
                return;
            }
            promise.cancel(true);

            int count = attempt + 1;
            readAsync(slot, asyncOperation, mainPromise, count);
        }
    };

    try {
        RedisConnection<Object, V> connection = connectionReadOp(slot);
        RedisAsyncConnection<Object, V> async = connection.getAsync();
        log.debug("readAsync for slot {} using {}", slot, connection.getRedisClient().getAddr());
        asyncOperation.execute(promise, async);

        ex.set(new RedisTimeoutException());
        Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS);
        promise.addListener(createReleaseReadListener(slot, connection, timeout));
    } catch (RedisConnectionException e) {
        ex.set(e);
        timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    promise.addListener(new FutureListener<T>() {
        @Override
        public void operationComplete(Future<T> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }
            // TODO cancel timeout

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                readAsync(ex.getSlot(), asyncOperation, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                mainPromise.setSuccess(future.getNow());
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}