Search in sources :

Example 36 with TimerTask

use of io.netty.util.TimerTask in project redisson by redisson.

the class CommandBatchService method executeRedisBasedQueue.

private <R> RFuture<R> executeRedisBasedQueue() {
    RPromise<R> resultPromise = new RedissonPromise<R>();
    long responseTimeout;
    if (options.getResponseTimeout() > 0) {
        responseTimeout = options.getResponseTimeout();
    } else {
        responseTimeout = connectionManager.getConfig().getTimeout();
    }
    Timeout timeout = connectionManager.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            connections.values().forEach(c -> {
                c.getCancelCallback().run();
            });
            resultPromise.tryFailure(new RedisTimeoutException("Response timeout for queued commands " + responseTimeout + ": " + commands.values().stream().flatMap(e -> e.getCommands().stream().map(d -> d.getCommand())).collect(Collectors.toList())));
        }
    }, responseTimeout, TimeUnit.MILLISECONDS);
    CompletableFuture<Void> allFutures = CompletableFuture.allOf(commands.values().stream().flatMap(m -> m.getCommands().stream().map(c -> ((BatchPromise) c.getPromise()).getSentPromise())).toArray(CompletableFuture[]::new));
    allFutures.whenComplete((fr, exc) -> {
        if (!timeout.cancel()) {
            return;
        }
        for (Entry entry : commands.values()) {
            for (BatchCommandData<?, ?> command : entry.getCommands()) {
                if (command.getPromise().isDone() && command.getPromise().isCompletedExceptionally()) {
                    resultPromise.tryFailure(cause(command.getPromise()));
                    break;
                }
            }
        }
        if (resultPromise.isDone()) {
            return;
        }
        Map<MasterSlaveEntry, List<Object>> result = new ConcurrentHashMap<>();
        List<CompletableFuture<Void>> futures = new ArrayList<>(commands.size());
        for (Map.Entry<MasterSlaveEntry, Entry> entry : commands.entrySet()) {
            RFuture<List<Object>> execPromise = async(entry.getValue().isReadOnlyMode(), new NodeSource(entry.getKey()), connectionManager.getCodec(), RedisCommands.EXEC, new Object[] {}, false, false);
            CompletionStage<Void> f = execPromise.thenCompose(r -> {
                BatchCommandData<?, Integer> lastCommand = (BatchCommandData<?, Integer>) entry.getValue().getCommands().peekLast();
                result.put(entry.getKey(), r);
                if (RedisCommands.WAIT.getName().equals(lastCommand.getCommand().getName())) {
                    return lastCommand.getPromise().thenApply(i -> null);
                }
                return CompletableFuture.completedFuture(null);
            });
            futures.add(f.toCompletableFuture());
        }
        CompletableFuture<Void> future = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        future.whenComplete((res, ex) -> {
            executed.set(true);
            if (ex != null) {
                resultPromise.tryFailure(ex);
                return;
            }
            try {
                for (java.util.Map.Entry<MasterSlaveEntry, List<Object>> entry : result.entrySet()) {
                    Entry commandEntry = commands.get(entry.getKey());
                    Iterator<Object> resultIter = entry.getValue().iterator();
                    for (BatchCommandData<?, ?> data : commandEntry.getCommands()) {
                        if (data.getCommand().getName().equals(RedisCommands.EXEC.getName())) {
                            break;
                        }
                        CompletableFuture<Object> promise = (CompletableFuture<Object>) data.getPromise();
                        if (resultIter.hasNext()) {
                            promise.complete(resultIter.next());
                        } else {
                            // fix for https://github.com/redisson/redisson/issues/2212
                            promise.complete(null);
                        }
                    }
                }
                List<BatchCommandData> entries = new ArrayList<>();
                for (Entry e : commands.values()) {
                    entries.addAll(e.getCommands());
                }
                Collections.sort(entries);
                List<Object> responses = new ArrayList<>(entries.size());
                int syncedSlaves = 0;
                for (BatchCommandData<?, ?> commandEntry : entries) {
                    if (isWaitCommand(commandEntry)) {
                        syncedSlaves += (Integer) commandEntry.getPromise().getNow(null);
                    } else if (!commandEntry.getCommand().getName().equals(RedisCommands.MULTI.getName()) && !commandEntry.getCommand().getName().equals(RedisCommands.EXEC.getName())) {
                        Object entryResult = commandEntry.getPromise().getNow(null);
                        if (objectBuilder != null) {
                            entryResult = objectBuilder.tryHandleReference(entryResult, referenceType);
                        }
                        responses.add(entryResult);
                    }
                }
                BatchResult<Object> r = new BatchResult<>(responses, syncedSlaves);
                resultPromise.trySuccess((R) r);
            } catch (Exception e) {
                resultPromise.tryFailure(e);
            }
        });
    });
    return resultPromise;
}
Also used : RPromise(org.redisson.misc.RPromise) java.util(java.util) RedisConnection(org.redisson.client.RedisConnection) Codec(org.redisson.client.codec.Codec) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionMode(org.redisson.api.BatchOptions.ExecutionMode) RFuture(org.redisson.api.RFuture) NodeSource(org.redisson.connection.NodeSource) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TimerTask(io.netty.util.TimerTask) BatchCommandData(org.redisson.client.protocol.BatchCommandData) Timeout(io.netty.util.Timeout) ConnectionManager(org.redisson.connection.ConnectionManager) java.util.concurrent(java.util.concurrent) RedissonPromise(org.redisson.misc.RedissonPromise) CommandData(org.redisson.client.protocol.CommandData) BatchOptions(org.redisson.api.BatchOptions) RedisTimeoutException(org.redisson.client.RedisTimeoutException) Collectors(java.util.stream.Collectors) BatchResult(org.redisson.api.BatchResult) RedisCommands(org.redisson.client.protocol.RedisCommands) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) RedisCommand(org.redisson.client.protocol.RedisCommand) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) RedissonPromise(org.redisson.misc.RedissonPromise) BatchCommandData(org.redisson.client.protocol.BatchCommandData) BatchResult(org.redisson.api.BatchResult) NodeSource(org.redisson.connection.NodeSource) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) TimerTask(io.netty.util.TimerTask) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) Timeout(io.netty.util.Timeout) RedisTimeoutException(org.redisson.client.RedisTimeoutException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RedisTimeoutException(org.redisson.client.RedisTimeoutException)

Example 37 with TimerTask

use of io.netty.util.TimerTask in project redisson by redisson.

the class RedisExecutor method scheduleRetryTimeout.

private void scheduleRetryTimeout(CompletableFuture<RedisConnection> connectionFuture, CompletableFuture<R> attemptPromise) {
    TimerTask retryTimerTask = new TimerTask() {

        @Override
        public void run(Timeout t) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (connectionFuture.cancel(false)) {
                exception = new RedisTimeoutException("Unable to acquire connection! " + connectionFuture + "Increase connection pool size. " + "Node source: " + source + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts");
            } else {
                if (connectionFuture.isDone() && !connectionFuture.isCompletedExceptionally()) {
                    if (writeFuture == null || !writeFuture.isDone()) {
                        if (attempt == attempts) {
                            if (writeFuture != null && writeFuture.cancel(false)) {
                                if (exception == null) {
                                    long totalSize = 0;
                                    if (params != null) {
                                        for (Object param : params) {
                                            if (param instanceof ByteBuf) {
                                                totalSize += ((ByteBuf) param).readableBytes();
                                            }
                                        }
                                    }
                                    exception = new RedisTimeoutException("Command still hasn't been written into connection! " + "Try to increase nettyThreads setting. Payload size in bytes: " + totalSize + ". Node source: " + source + ", connection: " + getNow(connectionFuture) + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts");
                                }
                                attemptPromise.completeExceptionally(exception);
                            }
                            return;
                        }
                        attempt++;
                        scheduleRetryTimeout(connectionFuture, attemptPromise);
                        return;
                    }
                    if (writeFuture.isSuccess()) {
                        return;
                    }
                }
            }
            if (mainPromise.isCancelled()) {
                if (attemptPromise.cancel(false)) {
                    free();
                }
                return;
            }
            if (attempt == attempts) {
                // filled out in connectionFuture or writeFuture handler
                if (exception != null) {
                    attemptPromise.completeExceptionally(exception);
                }
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }
            attempt++;
            if (log.isDebugEnabled()) {
                log.debug("attempt {} for command {} and params {}", attempt, command, LogHelper.toString(params));
            }
            mainPromiseListener = null;
            execute();
        }
    };
    timeout = connectionManager.newTimeout(retryTimerTask, retryInterval, TimeUnit.MILLISECONDS);
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ByteBuf(io.netty.buffer.ByteBuf)

Example 38 with TimerTask

use of io.netty.util.TimerTask in project netty-socketio by mrniko.

the class HashedWheelTimeoutScheduler method scheduleCallback.

@Override
public void scheduleCallback(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) {
    Timeout timeout = executorService.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            ctx.executor().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        runnable.run();
                    } finally {
                        scheduledFutures.remove(key);
                    }
                }
            });
        }
    }, delay, unit);
    replaceScheduledFuture(key, timeout);
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout)

Aggregations

Timeout (io.netty.util.Timeout)38 TimerTask (io.netty.util.TimerTask)38 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 AtomicLong (java.util.concurrent.atomic.AtomicLong)8 RFuture (org.redisson.api.RFuture)8 RedisTimeoutException (org.redisson.client.RedisTimeoutException)7 FutureListener (io.netty.util.concurrent.FutureListener)6 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelFuture (io.netty.channel.ChannelFuture)5 Future (io.netty.util.concurrent.Future)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 ArrayList (java.util.ArrayList)5 RedisException (org.redisson.client.RedisException)5 WriteRedisConnectionException (org.redisson.client.WriteRedisConnectionException)5 CompletableFutureWrapper (org.redisson.misc.CompletableFutureWrapper)5 RedisConnection (org.redisson.client.RedisConnection)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ChannelFutureListener (io.netty.channel.ChannelFutureListener)3 IOException (java.io.IOException)3