Search in sources :

Example 16 with TimerTask

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

the class RedissonBaseLock method renewExpiration.

private void renewExpiration() {
    ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
    if (ee == null) {
        return;
    }
    Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
            if (ent == null) {
                return;
            }
            Long threadId = ent.getFirstThreadId();
            if (threadId == null) {
                return;
            }
            RFuture<Boolean> future = renewExpirationAsync(threadId);
            future.whenComplete((res, e) -> {
                if (e != null) {
                    log.error("Can't update lock " + getRawName() + " expiration", e);
                    EXPIRATION_RENEWAL_MAP.remove(getEntryName());
                    return;
                }
                if (res) {
                    // reschedule itself
                    renewExpiration();
                } else {
                    cancelExpirationRenewal(null);
                }
            });
        }
    }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
    ee.setTimeout(task);
}
Also used : Timeout(io.netty.util.Timeout) LongCodec(org.redisson.client.codec.LongCodec) CommandAsyncExecutor(org.redisson.command.CommandAsyncExecutor) Logger(org.slf4j.Logger) Codec(org.redisson.client.codec.Codec) CommandBatchService(org.redisson.command.CommandBatchService) java.util.concurrent(java.util.concurrent) LoggerFactory(org.slf4j.LoggerFactory) BatchOptions(org.redisson.api.BatchOptions) BatchResult(org.redisson.api.BatchResult) RedisCommands(org.redisson.client.protocol.RedisCommands) RFuture(org.redisson.api.RFuture) LinkedHashMap(java.util.LinkedHashMap) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) MapValueDecoder(org.redisson.client.protocol.decoder.MapValueDecoder) List(java.util.List) Condition(java.util.concurrent.locks.Condition) RLock(org.redisson.api.RLock) Map(java.util.Map) MasterSlaveEntry(org.redisson.connection.MasterSlaveEntry) TimerTask(io.netty.util.TimerTask) RedisCommand(org.redisson.client.protocol.RedisCommand) IntegerReplayConvertor(org.redisson.client.protocol.convertor.IntegerReplayConvertor) Collections(java.util.Collections) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) RFuture(org.redisson.api.RFuture)

Example 17 with TimerTask

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

the class QueueTransferTask method scheduleTask.

private void scheduleTask(final Long startTime) {
    TimeoutTask oldTimeout = lastTimeout.get();
    if (startTime == null) {
        return;
    }
    if (oldTimeout != null) {
        oldTimeout.getTask().cancel();
    }
    long delay = startTime - System.currentTimeMillis();
    if (delay > 10) {
        Timeout timeout = connectionManager.newTimeout(new TimerTask() {

            @Override
            public void run(Timeout timeout) throws Exception {
                pushTask();
                TimeoutTask currentTimeout = lastTimeout.get();
                if (currentTimeout.getTask() == timeout) {
                    lastTimeout.compareAndSet(currentTimeout, null);
                }
            }
        }, delay, TimeUnit.MILLISECONDS);
        if (!lastTimeout.compareAndSet(oldTimeout, new TimeoutTask(startTime, timeout))) {
            timeout.cancel();
        }
    } else {
        pushTask();
    }
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout)

Example 18 with TimerTask

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

the class RedisExecutor method scheduleResponseTimeout.

private void scheduleResponseTimeout(CompletableFuture<R> attemptPromise, RedisConnection connection) {
    long timeoutTime = responseTimeout;
    if (command != null && command.isBlockingCommand()) {
        Long popTimeout = null;
        if (RedisCommands.BLOCKING_COMMANDS.contains(command)) {
            for (int i = 0; i < params.length - 1; i++) {
                if ("BLOCK".equals(params[i])) {
                    popTimeout = Long.valueOf(params[i + 1].toString()) / 1000;
                    break;
                }
            }
        } else {
            popTimeout = Long.valueOf(params[params.length - 1].toString());
        }
        handleBlockingOperations(attemptPromise, connection, popTimeout);
        if (popTimeout == 0) {
            return;
        }
        timeoutTime += popTimeout * 1000;
        // add 1 second due to issue https://github.com/antirez/redis/issues/874
        timeoutTime += 1000;
    }
    long timeoutAmount = timeoutTime;
    TimerTask timeoutResponseTask = timeout -> {
        if (isResendAllowed(attempt, attempts)) {
            if (!attemptPromise.cancel(false)) {
                return;
            }
            connectionManager.newTimeout(t -> {
                attempt++;
                if (log.isDebugEnabled()) {
                    log.debug("attempt {} for command {} and params {}", attempt, command, LogHelper.toString(params));
                }
                mainPromiseListener = null;
                execute();
            }, retryInterval, TimeUnit.MILLISECONDS);
            return;
        }
        attemptPromise.completeExceptionally(new RedisResponseTimeoutException("Redis server response timeout (" + timeoutAmount + " ms) occured" + " after " + attempt + " retry attempts. Increase nettyThreads and/or timeout settings. Try to define pingConnectionInterval setting. Command: " + LogHelper.toString(command, params) + ", channel: " + connection.getChannel()));
    };
    timeout = connectionManager.newTimeout(timeoutResponseTask, timeoutTime, TimeUnit.MILLISECONDS);
}
Also used : Codec(org.redisson.client.codec.Codec) LoggerFactory(org.slf4j.LoggerFactory) RedisURI(org.redisson.misc.RedisURI) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) BaseCodec(org.redisson.client.codec.BaseCodec) NodeSource(org.redisson.connection.NodeSource) ByteBuf(io.netty.buffer.ByteBuf) ScanResult(org.redisson.ScanResult) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) FutureListener(io.netty.util.concurrent.FutureListener) CancellationException(java.util.concurrent.CancellationException) LRUCacheMap(org.redisson.cache.LRUCacheMap) ConnectionManager(org.redisson.connection.ConnectionManager) org.redisson.client(org.redisson.client) CommandData(org.redisson.client.protocol.CommandData) CompletionException(java.util.concurrent.CompletionException) Redirect(org.redisson.connection.NodeSource.Redirect) RedissonShutdownException(org.redisson.RedissonShutdownException) ChannelFuture(io.netty.channel.ChannelFuture) RedisCommands(org.redisson.client.protocol.RedisCommands) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) RedisCommand(org.redisson.client.protocol.RedisCommand) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) CommandsData(org.redisson.client.protocol.CommandsData) LogHelper(org.redisson.misc.LogHelper) TimerTask(io.netty.util.TimerTask)

Example 19 with TimerTask

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

the class RedissonTransaction method disableLocalCacheAsync.

private CompletableFuture<Map<HashKey, HashValue>> disableLocalCacheAsync(String requestId, Set<String> localCaches, List<TransactionalOperation> operations) {
    if (localCaches.isEmpty()) {
        return CompletableFuture.completedFuture(Collections.emptyMap());
    }
    CompletableFuture<Map<HashKey, HashValue>> result = new CompletableFuture<>();
    Map<HashKey, HashValue> hashes = new HashMap<>(localCaches.size());
    RedissonBatch batch = createBatch();
    for (TransactionalOperation transactionalOperation : operations) {
        if (localCaches.contains(transactionalOperation.getName())) {
            MapOperation mapOperation = (MapOperation) transactionalOperation;
            RedissonLocalCachedMap<?, ?> map = (RedissonLocalCachedMap<?, ?>) mapOperation.getMap();
            HashKey hashKey = new HashKey(transactionalOperation.getName(), transactionalOperation.getCodec());
            byte[] key = map.getLocalCacheView().toCacheKey(mapOperation.getKey()).getKeyHash();
            HashValue value = hashes.get(hashKey);
            if (value == null) {
                value = new HashValue();
                hashes.put(hashKey, value);
            }
            value.getKeyIds().add(key);
            String disabledKeysName = RedissonObject.suffixName(transactionalOperation.getName(), RedissonLocalCachedMap.DISABLED_KEYS_SUFFIX);
            RMultimapCacheAsync<LocalCachedMapDisabledKey, String> multimap = batch.getListMultimapCache(disabledKeysName, transactionalOperation.getCodec());
            LocalCachedMapDisabledKey localCacheKey = new LocalCachedMapDisabledKey(requestId, options.getResponseTimeout());
            multimap.putAsync(localCacheKey, ByteBufUtil.hexDump(key));
            multimap.expireKeyAsync(localCacheKey, options.getResponseTimeout(), TimeUnit.MILLISECONDS);
        }
    }
    RFuture<BatchResult<?>> batchListener = batch.executeAsync();
    batchListener.onComplete((res, e) -> {
        if (e != null) {
            result.completeExceptionally(e);
            return;
        }
        AsyncCountDownLatch latch = new AsyncCountDownLatch();
        latch.latch(() -> {
            result.complete(hashes);
        }, hashes.size());
        List<CompletableFuture<?>> subscriptionFutures = new ArrayList<>();
        List<RTopic> topics = new ArrayList<>();
        for (Entry<HashKey, HashValue> entry : hashes.entrySet()) {
            String disabledAckName = RedissonObject.suffixName(entry.getKey().getName(), requestId + RedissonLocalCachedMap.DISABLED_ACK_SUFFIX);
            RTopic topic = RedissonTopic.createRaw(LocalCachedMessageCodec.INSTANCE, commandExecutor, disabledAckName);
            topics.add(topic);
            RFuture<Integer> topicFuture = topic.addListenerAsync(Object.class, (channel, msg) -> {
                AtomicInteger counter = entry.getValue().getCounter();
                if (counter.decrementAndGet() == 0) {
                    latch.countDown();
                }
            });
            subscriptionFutures.add(topicFuture.toCompletableFuture());
        }
        CompletableFuture<Void> subscriptionFuture = CompletableFuture.allOf(subscriptionFutures.toArray(new CompletableFuture[0]));
        subscriptionFuture.whenComplete((r, ex) -> {
            RedissonBatch publishBatch = createBatch();
            for (Entry<HashKey, HashValue> entry : hashes.entrySet()) {
                String disabledKeysName = RedissonObject.suffixName(entry.getKey().getName(), RedissonLocalCachedMap.DISABLED_KEYS_SUFFIX);
                RMultimapCacheAsync<LocalCachedMapDisabledKey, String> multimap = publishBatch.getListMultimapCache(disabledKeysName, entry.getKey().getCodec());
                LocalCachedMapDisabledKey localCacheKey = new LocalCachedMapDisabledKey(requestId, options.getResponseTimeout());
                multimap.removeAllAsync(localCacheKey);
                RTopicAsync topic = publishBatch.getTopic(RedissonObject.suffixName(entry.getKey().getName(), RedissonLocalCachedMap.TOPIC_SUFFIX), LocalCachedMessageCodec.INSTANCE);
                RFuture<Long> publishFuture = topic.publishAsync(new LocalCachedMapDisable(requestId, entry.getValue().getKeyIds().toArray(new byte[entry.getValue().getKeyIds().size()][]), options.getResponseTimeout()));
                publishFuture.onComplete((receivers, exc) -> {
                    if (ex != null) {
                        return;
                    }
                    AtomicInteger counter = entry.getValue().getCounter();
                    if (counter.addAndGet(receivers.intValue()) == 0) {
                        latch.countDown();
                    }
                });
            }
            RFuture<BatchResult<?>> publishFuture = publishBatch.executeAsync();
            publishFuture.onComplete((res2, ex2) -> {
                result.whenComplete((res3, ex3) -> {
                    for (RTopic topic : topics) {
                        topic.removeAllListeners();
                    }
                });
                if (ex2 != null) {
                    result.completeExceptionally(ex2);
                    return;
                }
                commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        result.completeExceptionally(new TransactionTimeoutException("Unable to execute transaction within " + options.getResponseTimeout() + "ms"));
                    }
                }, options.getResponseTimeout(), TimeUnit.MILLISECONDS);
            });
        });
    });
    return result;
}
Also used : MapOperation(org.redisson.transaction.operation.map.MapOperation) TimerTask(io.netty.util.TimerTask) LocalCachedMapDisabledKey(org.redisson.cache.LocalCachedMapDisabledKey) LocalCachedMapDisable(org.redisson.cache.LocalCachedMapDisable) RedissonBatch(org.redisson.RedissonBatch) Timeout(io.netty.util.Timeout) TransactionalOperation(org.redisson.transaction.operation.TransactionalOperation) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncCountDownLatch(org.redisson.misc.AsyncCountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RedissonLocalCachedMap(org.redisson.RedissonLocalCachedMap) RedissonLocalCachedMap(org.redisson.RedissonLocalCachedMap)

Example 20 with TimerTask

use of io.netty.util.TimerTask in project pinpoint by naver.

the class MetadataClientMock method scheduleNextRetry.

private void scheduleNextRetry(GeneratedMessageV3 request, int remainingRetryCount) {
    final TimerTask timerTask = new TimerTask() {

        @Override
        public void run(Timeout timeout) {
            if (timeout.cancel()) {
                return;
            }
            logger.info("Retry {} {}", remainingRetryCount, request);
            request(request, remainingRetryCount - 1);
        }
    };
    try {
        retryTimer.newTimeout(timerTask, 1000, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException e) {
        logger.debug("retry fail {}", e.getCause(), e);
    }
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

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