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

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

Introduction

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

Prototype

Promise<V> setSuccess(V result);

Source Link

Document

Marks this future as a success and notifies all listeners.

Usage

From source file:org.redisson.CommandExecutorService.java

License:Apache License

public <T, R> Future<Collection<R>> readAllAsync(RedisCommand<T> command, Object... params) {
    final Promise<Collection<R>> mainPromise = connectionManager.newPromise();
    Promise<R> promise = new DefaultPromise<R>() {
        Queue<R> results = new ConcurrentLinkedQueue<R>();
        AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size());

        @Override// w  w w. j  ava2s .  c  o  m
        public Promise<R> setSuccess(R result) {
            if (result instanceof Collection) {
                results.addAll((Collection) result);
            } else {
                results.add(result);
            }

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

        @Override
        public Promise<R> setFailure(Throwable cause) {
            mainPromise.setFailure(cause);
            return this;
        }

    };

    for (Integer slot : connectionManager.getEntries().keySet()) {
        async(true, slot, null, connectionManager.getCodec(), command, params, promise, 0);
    }
    return mainPromise;
}

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//w ww. j  a 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 <T, R> Future<R> allAsync(boolean readOnlyMode, RedisCommand<T> command,
        final SlotCallback<T, R> callback, Object... params) {
    final Promise<R> mainPromise = connectionManager.newPromise();
    Promise<T> promise = new DefaultPromise<T>() {
        AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size());

        @Override//from   w  ww.j  a v  a2s .c o  m
        public Promise<T> setSuccess(T result) {
            if (callback != null) {
                callback.onSlotResult(result);
            }
            if (counter.decrementAndGet() == 0) {
                if (callback != null) {
                    mainPromise.setSuccess(callback.onFinish());
                } else {
                    mainPromise.setSuccess(null);
                }
            }
            return this;
        }

        @Override
        public Promise<T> setFailure(Throwable cause) {
            mainPromise.setFailure(cause);
            return this;
        }
    };
    for (Integer slot : connectionManager.getEntries().keySet()) {
        async(readOnlyMode, slot, null, connectionManager.getCodec(), command, params, promise, 0);
    }
    return mainPromise;
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

public <T, R> Future<R> evalAllAsync(boolean readOnlyMode, RedisCommand<T> command,
        final SlotCallback<T, R> callback, String script, List<Object> keys, Object... params) {
    final Promise<R> mainPromise = connectionManager.newPromise();
    Promise<T> promise = new DefaultPromise<T>() {
        AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size());

        @Override/*from ww w. j  a  v a2  s  . c  o m*/
        public Promise<T> setSuccess(T result) {
            callback.onSlotResult(result);
            if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                mainPromise.setSuccess(callback.onFinish());
            }
            return this;
        }

        @Override
        public Promise<T> setFailure(Throwable cause) {
            mainPromise.setFailure(cause);
            return this;
        }
    };

    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 (Integer slot : connectionManager.getEntries().keySet()) {
        async(readOnlyMode, slot, null, connectionManager.getCodec(), command, args.toArray(), promise, 0);
    }
    return mainPromise;
}

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;/*  ww w.j av  a 2  s . c  om*/
    }

    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//from   w  ww  .  jav a2  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 .j  av a2s.  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;
            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 ww  w .j  a  v a 2  s.  com*/
        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());
            }
        }
    });
}

From source file:org.redisson.core.RedissonMultiLock.java

License:Apache License

private void lock(final Promise<Void> promise, final long waitTime, final long leaseTime, final TimeUnit unit)
        throws InterruptedException {
    final AtomicInteger tryLockRequestsAmount = new AtomicInteger();
    final Map<Future<Boolean>, RLock> tryLockFutures = new HashMap<Future<Boolean>, RLock>(locks.size());

    FutureListener<Boolean> listener = new FutureListener<Boolean>() {

        AtomicBoolean unlock = new AtomicBoolean();

        @Override/* ww w .j  a va2 s .c  o m*/
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                // unlock once
                if (unlock.compareAndSet(false, true)) {
                    for (RLock lock : locks) {
                        lock.unlockAsync();
                    }

                    promise.setFailure(future.cause());
                }
                return;
            }

            Boolean res = future.getNow();
            // unlock once
            if (!res && unlock.compareAndSet(false, true)) {
                for (RLock lock : locks) {
                    lock.unlockAsync();
                }

                RLock lock = tryLockFutures.get(future);
                lock.lockAsync().addListener(new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        if (!future.isSuccess()) {
                            promise.setFailure(future.cause());
                            return;
                        }

                        lock(promise, waitTime, leaseTime, unit);
                    }
                });
            }
            if (!unlock.get() && tryLockRequestsAmount.decrementAndGet() == 0) {
                promise.setSuccess(null);
            }
        }
    };

    for (RLock lock : locks) {
        if (lock.isHeldByCurrentThread()) {
            continue;
        }

        tryLockRequestsAmount.incrementAndGet();
        if (waitTime > 0 || leaseTime > 0) {
            tryLockFutures.put(lock.tryLockAsync(waitTime, leaseTime, unit), lock);
        } else {
            tryLockFutures.put(lock.tryLockAsync(), lock);
        }
    }

    for (Future<Boolean> future : tryLockFutures.keySet()) {
        future.addListener(listener);
    }
}

From source file:org.redisson.misc.ConnectionPool.java

License:Apache License

private void initConnections(final ClientConnectionsEntry entry, final Promise<Void> initPromise,
        boolean checkFreezed) {
    int minimumIdleSize = getMinimumIdleSize(entry);

    if (minimumIdleSize == 0 || (checkFreezed && entry.isFreezed())) {
        initPromise.setSuccess(null);
        return;/* w w w.  j  a  v  a2  s.com*/
    }

    final AtomicInteger initializedConnections = new AtomicInteger(minimumIdleSize);
    for (int i = 0; i < minimumIdleSize; i++) {
        if ((checkFreezed && entry.isFreezed()) || !tryAcquireConnection(entry)) {
            Throwable cause = new RedisConnectionException(
                    "Can't init enough connections amount! " + initializedConnections.get() + " from "
                            + minimumIdleSize + " was initialized. Server: " + entry.getClient().getAddr());
            initPromise.tryFailure(cause);
            return;
        }

        Future<T> promise = connectTo(entry);
        promise.addListener(new FutureListener<T>() {
            @Override
            public void operationComplete(Future<T> future) throws Exception {
                if (future.isSuccess()) {
                    T conn = future.getNow();
                    releaseConnection(entry, conn);
                }
                releaseConnection(entry);
                if (!future.isSuccess()) {
                    Throwable cause = new RedisConnectionException(
                            "Can't init enough connections amount! from " + entry.getClient().getAddr());
                    initPromise.tryFailure(cause);
                    return;
                }

                if (initializedConnections.decrementAndGet() == 0) {
                    initPromise.setSuccess(null);
                }
            }
        });
    }
}