Java Code Examples for org.redisson.api.RFuture#onComplete()

The following examples show how to use org.redisson.api.RFuture#onComplete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PublishSubscribeService.java    From redisson with Apache License 2.0 6 votes vote down vote up
private void reattachPubSubListeners(ChannelName channelName, Collection<RedisPubSubListener<?>> listeners, PubSubType topicType) {
    RFuture<Codec> subscribeCodecFuture = unsubscribe(channelName, topicType);
    if (listeners.isEmpty()) {
        return;
    }
    
    subscribeCodecFuture.onComplete((subscribeCodec, e) -> {
        if (subscribeCodec == null) {
            return;
        }
        
        if (topicType == PubSubType.PUNSUBSCRIBE) {
            psubscribe(channelName, listeners, subscribeCodec);
        } else {
            subscribe(channelName, listeners, subscribeCodec);
        }
    });
}
 
Example 2
Source File: RedissonMap.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public RFuture<V> getAsync(K key) {
    checkKey(key);

    RFuture<V> future = getOperationAsync(key);
    if (hasNoLoader()) {
        return future;
    }
    
    RPromise<V> result = new RedissonPromise<>();
    future.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        if (res == null) {
            loadValue(key, result, false);
        } else {
            result.trySuccess(res);
        }
    });
    return result;
}
 
Example 3
Source File: RedisClientEntry.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public RFuture<Boolean> pingAsync(long timeout, TimeUnit timeUnit) {
    RPromise<Boolean> result = new RedissonPromise<>();
    RFuture<Boolean> f = commandExecutor.readAsync(client, null, RedisCommands.PING_BOOL);
    f.onComplete((res, e) -> {
        if (e != null) {
            result.trySuccess(false);
            return;
        }
        
        result.trySuccess(res);
    });
    commandExecutor.getConnectionManager().newTimeout(t -> {
        RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for command: PING, Redis client: " + client);
        result.tryFailure(ex);
    }, timeout, timeUnit);
    return result;
}
 
Example 4
Source File: RedissonPermitExpirableSemaphore.java    From redisson with Apache License 2.0 6 votes vote down vote up
public RFuture<String> tryAcquireAsync() {
    RPromise<String> result = new RedissonPromise<String>();
    RFuture<String> future = tryAcquireAsync(1, nonExpirableTimeout);
    future.onComplete((permitId, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        if (permitId != null && !permitId.startsWith(":")) {
            if (!result.trySuccess(permitId)) {
                releaseAsync(permitId);
            }
        } else {
            result.trySuccess(null);
        }
    });
    return result;
}
 
Example 5
Source File: RedissonBoundedBlockingQueue.java    From redisson with Apache License 2.0 6 votes vote down vote up
private RPromise<V> wrapTakeFuture(RFuture<V> takeFuture) {
    RPromise<V> result = new RedissonPromise<V>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            super.cancel(mayInterruptIfRunning);
            return takeFuture.cancel(mayInterruptIfRunning);
        };
    };
    
    takeFuture.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        if (res == null) {
            result.trySuccess(takeFuture.getNow());
            return;
        }
        createSemaphore(null).releaseAsync().onComplete((r, ex) -> {
            result.trySuccess(takeFuture.getNow());
        });
    });
    return result;
}
 
Example 6
Source File: RedissonTransaction.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public RFuture<Void> rollbackAsync() {
    checkState();

    CommandBatchService executorService = new CommandBatchService(commandExecutor.getConnectionManager());
    for (TransactionalOperation transactionalOperation : operations) {
        transactionalOperation.rollback(executorService);
    }

    RPromise<Void> result = new RedissonPromise<>();
    RFuture<BatchResult<?>> future = executorService.executeAsync();
    future.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(new TransactionException("Unable to rollback transaction", e));
            return;
        }
        
        operations.clear();
        executed.set(true);
        result.trySuccess(null);
    });
    return result;
}
 
Example 7
Source File: RedissonSemaphore.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void acquireAsync(int permits, RFuture<RedissonLockEntry> subscribeFuture, RPromise<Void> result) {
    if (result.isDone()) {
        unsubscribe(subscribeFuture);
        return;
    }

    RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits);
    tryAcquireFuture.onComplete((res, e) -> {
        if (e != null) {
            unsubscribe(subscribeFuture);
            result.tryFailure(e);
            return;
        }

        if (res) {
            unsubscribe(subscribeFuture);
            if (!result.trySuccess(null)) {
                releaseAsync(permits);
            }
            return;
        }
        
        RedissonLockEntry entry = subscribeFuture.getNow();
        if (entry.getLatch().tryAcquire(permits)) {
            acquireAsync(permits, subscribeFuture, result);
        } else {
            entry.addListener(() -> {
                acquireAsync(permits, subscribeFuture, result);
            });
        }
    });
}
 
Example 8
Source File: RedissonLocalCachedMap.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected RFuture<V> addAndGetOperationAsync(K key, Number value) {
    ByteBuf keyState = encodeMapKey(key);
    CacheKey cacheKey = toCacheKey(keyState);
    ByteBuf msg = encode(new LocalCachedMapInvalidate(instanceId, cacheKey.getKeyHash()));
    byte[] entryId = generateLogEntryId(cacheKey.getKeyHash());
    RFuture<V> future = commandExecutor.evalWriteAsync(getName(), StringCodec.INSTANCE, new RedisCommand<Object>("EVAL", new NumberConvertor(value.getClass())),
            "local result = redis.call('HINCRBYFLOAT', KEYS[1], ARGV[1], ARGV[2]); "
          + "if ARGV[3] == '1' then "
               + "redis.call('publish', KEYS[2], ARGV[4]); "
          + "end;"
          + "if ARGV[3] == '2' then "
               + "redis.call('zadd', KEYS[3], ARGV[5], ARGV[6]);"
               + "redis.call('publish', KEYS[2], ARGV[4]); "
          + "end;"
          + "return result; ",
          Arrays.<Object>asList(getName(), listener.getInvalidationTopicName(), listener.getUpdatesLogName()), 
          keyState, new BigDecimal(value.toString()).toPlainString(), invalidateEntryOnChange, msg, System.currentTimeMillis(), entryId);

    future.onComplete((res, e) -> {
        if (res != null) {
            CacheKey cKey = toCacheKey(key);
            cachePut(cKey, key, res);
        }
    });
    return future;
}
 
Example 9
Source File: TasksRunnerService.java    From redisson with Apache License 2.0 5 votes vote down vote up
protected RFuture<Long> renewRetryTime(String requestId) {
    RFuture<Long> future = commandExecutor.evalWriteAsync(name, LongCodec.INSTANCE, RedisCommands.EVAL_LONG,
            // check if executor service not in shutdown state
              "local name = ARGV[2];"
            + "local scheduledName = ARGV[2];"
            + "if string.sub(scheduledName, 1, 2) ~= 'ff' then "
                + "scheduledName = 'ff' .. scheduledName; "
            + "else "
                + "name = string.sub(name, 3, string.len(name)); "
            + "end;"
            + "local retryInterval = redis.call('get', KEYS[4]);"
            
            + "if redis.call('exists', KEYS[1]) == 0 and retryInterval ~= false and redis.call('hexists', KEYS[5], name) == 1 then "
                + "local startTime = tonumber(ARGV[1]) + tonumber(retryInterval);"
                + "redis.call('zadd', KEYS[2], startTime, scheduledName);"
                + "local v = redis.call('zrange', KEYS[2], 0, 0); "
                // if new task added to queue head then publish its startTime 
                // to all scheduler workers 
                + "if v[1] == ARGV[2] then "
                    + "redis.call('publish', KEYS[3], startTime); "
                + "end;"
                + "return retryInterval; "
            + "end;"
            + "return nil;", 
            Arrays.<Object>asList(statusName, schedulerQueueName, schedulerChannelName, tasksRetryIntervalName, tasksName),
            System.currentTimeMillis(), requestId);
    future.onComplete((res, e) -> {
        if (e != null) {
            scheduleRetryTimeRenewal(requestId, 10000L);
            return;
        }
        
        if (res != null) {
            scheduleRetryTimeRenewal(requestId, res);
        }
    });
    return future;
}
 
Example 10
Source File: SentinelConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
private RFuture<Void> registerSentinel(RedisURI addr, MasterSlaveServersConfig c, String sslHostname) {
    RedisClient sentinel = sentinels.get(addr);
    if (sentinel != null) {
        return RedissonPromise.newSucceededFuture(null);
    }
    
    RedisClient client = createClient(NodeType.SENTINEL, addr, c.getConnectTimeout(), c.getTimeout(), sslHostname);
    RPromise<Void> result = new RedissonPromise<Void>();
    RFuture<InetSocketAddress> future = client.resolveAddr();
    future.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }

        RFuture<RedisConnection> f = client.connectAsync();
        f.onComplete((connection, ex) -> {
            if (ex != null) {
                result.tryFailure(ex);
                return;
            }

            RFuture<String> r = connection.async(RedisCommands.PING);
            r.onComplete((resp, exc) -> {
                if (exc != null) {
                    result.tryFailure(exc);
                    return;
                }
                
                if (sentinels.putIfAbsent(addr, client) == null) {
                    log.info("sentinel: {} added", addr);
                }
                result.trySuccess(null);
            });
        });

    });
    return result;
}
 
Example 11
Source File: ClientConnectionsEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<RedisConnection> connect() {
    RFuture<RedisConnection> future = client.connectAsync();
    future.onComplete((conn, e) -> {
        if (e != null) {
            return;
        }
        
        onConnect(conn);
        log.debug("new connection created: {}", conn);
        
        allConnections.add(conn);
    });
    return future;
}
 
Example 12
Source File: ClientConnectionsEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<RedisPubSubConnection> connectPubSub() {
    RFuture<RedisPubSubConnection> future = client.connectPubSubAsync();
    future.onComplete((res, e) -> {
        if (e != null) {
            return;
        }
        
        RedisPubSubConnection conn = future.getNow();
        onConnect(conn);
        log.debug("new pubsub connection created: {}", conn);

        allSubscribeConnections.add(conn);
    });
    return future;
}
 
Example 13
Source File: RedissonPermitExpirableSemaphore.java    From redisson with Apache License 2.0 5 votes vote down vote up
private RFuture<String> acquireAsync(int permits, long ttl, TimeUnit timeUnit) {
    RPromise<String> result = new RedissonPromise<String>();
    long timeoutDate = calcTimeout(ttl, timeUnit);
    RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
    tryAcquireFuture.onComplete((permitId, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }

        if (permitId != null && !permitId.startsWith(":")) {
            if (!result.trySuccess(permitId)) {
                releaseAsync(permitId);
            }
            return;
        }

        RFuture<RedissonLockEntry> subscribeFuture = subscribe();
        subscribeFuture.onComplete((res, ex) -> {
            if (ex != null) {
                result.tryFailure(ex);
                return;
            }
            
            acquireAsync(permits, subscribeFuture, result, ttl, timeUnit);
        });
    });
    return result;
}
 
Example 14
Source File: RedissonPatternTopic.java    From redisson with Apache License 2.0 5 votes vote down vote up
private RFuture<Integer> addListenerAsync(RedisPubSubListener<?> pubSubListener) {
    RFuture<PubSubConnectionEntry> future = subscribeService.psubscribe(channelName, codec, pubSubListener);
    RPromise<Integer> result = new RedissonPromise<Integer>();
    future.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        result.trySuccess(System.identityHashCode(pubSubListener));
    });
    return result;
}
 
Example 15
Source File: MasterSlaveEntry.java    From redisson with Apache License 2.0 5 votes vote down vote up
private RFuture<RedisClient> setupMasterEntry(RedisClient client) {
    RPromise<RedisClient> result = new RedissonPromise<RedisClient>();
    result.onComplete((res, e) -> {
        if (e != null) {
            client.shutdownAsync();
        }
    });
    RFuture<InetSocketAddress> addrFuture = client.resolveAddr();
    addrFuture.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        masterEntry = new ClientConnectionsEntry(
                client, 
                config.getMasterConnectionMinimumIdleSize(), 
                config.getMasterConnectionPoolSize(),
                config.getSubscriptionConnectionMinimumIdleSize(),
                config.getSubscriptionConnectionPoolSize(), 
                connectionManager,
                NodeType.MASTER);

        int counter = 1;
        if (config.getSubscriptionMode() == SubscriptionMode.MASTER) {
            counter++;
        }
        
        CountableListener<RedisClient> listener = new CountableListener<>(result, client, counter);
        RFuture<Void> writeFuture = writeConnectionPool.add(masterEntry);
        writeFuture.onComplete(listener);
        
        if (config.getSubscriptionMode() == SubscriptionMode.MASTER) {
            RFuture<Void> pubSubFuture = pubSubConnectionPool.add(masterEntry);
            pubSubFuture.onComplete(listener);
        }
    });
    
    return result;
}
 
Example 16
Source File: RedissonBaseReactive.java    From redisson with Apache License 2.0 5 votes vote down vote up
RFuture<String> toStringFuture(RFuture<Void> f) {
    RPromise<String> promise = new RedissonPromise<>();
    f.onComplete((res, e) -> {
        if (e != null) {
            promise.tryFailure(e);
            return;
        }
        
        promise.trySuccess("OK");
    });
    return promise;
}
 
Example 17
Source File: TasksService.java    From redisson with Apache License 2.0 5 votes vote down vote up
public RFuture<Boolean> cancelExecutionAsync(final RequestId requestId) {
    final RPromise<Boolean> result = new RedissonPromise<Boolean>();
    
    String requestQueueName = getRequestQueueName(RemoteExecutorService.class);
    RFuture<Boolean> removeFuture = removeAsync(requestQueueName, requestId);
    removeFuture.onComplete((res, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }
        
        if (res) {
            result.trySuccess(true);
            return;
        }
        
        RMap<String, RemoteServiceCancelRequest> canceledRequests = getMap(cancelRequestMapName);
        canceledRequests.putAsync(requestId.toString(), new RemoteServiceCancelRequest(true, true));
        canceledRequests.expireAsync(60, TimeUnit.SECONDS);
        
        final RPromise<RemoteServiceCancelResponse> response = new RedissonPromise<RemoteServiceCancelResponse>();
        scheduleCheck(cancelResponseMapName, requestId, response);
        response.onComplete((r, ex) -> {
            if (ex != null) {
                result.tryFailure(ex);
                return;
            }
            
            if (response.getNow() == null) {
                result.trySuccess(false);
                return;
            }
            result.trySuccess(response.getNow().isCanceled());
        });
    });

    return result;
}
 
Example 18
Source File: RedissonLock.java    From redisson with Apache License 2.0 4 votes vote down vote up
private void lockAsync(long leaseTime, TimeUnit unit,
        RFuture<RedissonLockEntry> subscribeFuture, RPromise<Void> result, long currentThreadId) {
    RFuture<Long> ttlFuture = tryAcquireAsync(leaseTime, unit, currentThreadId);
    ttlFuture.onComplete((ttl, e) -> {
        if (e != null) {
            unsubscribe(subscribeFuture, currentThreadId);
            result.tryFailure(e);
            return;
        }

        // lock acquired
        if (ttl == null) {
            unsubscribe(subscribeFuture, currentThreadId);
            if (!result.trySuccess(null)) {
                unlockAsync(currentThreadId);
            }
            return;
        }

        RedissonLockEntry entry = subscribeFuture.getNow();
        if (entry.getLatch().tryAcquire()) {
            lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId);
        } else {
            // waiting for message
            AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
            Runnable listener = () -> {
                if (futureRef.get() != null) {
                    futureRef.get().cancel();
                }
                lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId);
            };

            entry.addListener(listener);

            if (ttl >= 0) {
                Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (entry.removeListener(listener)) {
                            lockAsync(leaseTime, unit, subscribeFuture, result, currentThreadId);
                        }
                    }
                }, ttl, TimeUnit.MILLISECONDS);
                futureRef.set(scheduledFuture);
            }
        }
    });
}
 
Example 19
Source File: EvictionTask.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Override
    public void run() {
        if (executor.getConnectionManager().isShuttingDown()) {
            return;
        }
        
        RFuture<Integer> future = execute();
        future.onComplete((size, e) -> {
            if (e != null) {
                schedule();
                return;
            }

            log.debug("{} elements evicted. Object name: {}", size, getName());
            
            if (size == -1) {
                schedule();
                return;
            }

            if (sizeHistory.size() == 2) {
                if (sizeHistory.peekFirst() > sizeHistory.peekLast()
                        && sizeHistory.peekLast() > size) {
                    delay = Math.min(maxDelay, (int) (delay*1.5));
                }

//                    if (sizeHistory.peekFirst() < sizeHistory.peekLast()
//                            && sizeHistory.peekLast() < size) {
//                        prevDelay = Math.max(minDelay, prevDelay/2);
//                    }

                if (sizeHistory.peekFirst().intValue() == sizeHistory.peekLast()
                        && sizeHistory.peekLast().intValue() == size) {
                    if (size >= keysLimit) {
                        delay = Math.max(minDelay, delay/4);
                    }
                    if (size == 0) {
                        delay = Math.min(maxDelay, (int) (delay*1.5));
                    }
                }

                sizeHistory.pollFirst();
            }

            sizeHistory.add(size);
            schedule();
        });
    }
 
Example 20
Source File: RedissonCountDownLatch.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Override
public RFuture<Boolean> awaitAsync(long waitTime, TimeUnit unit) {
    RPromise<Boolean> result = new RedissonPromise<>();

    AtomicLong time = new AtomicLong(unit.toMillis(waitTime));
    long currentTime = System.currentTimeMillis();
    RFuture<Long> countFuture = getCountAsync();
    countFuture.onComplete((r, e) -> {
        if (e != null) {
            result.tryFailure(e);
            return;
        }

        long el = System.currentTimeMillis() - currentTime;
        time.addAndGet(-el);

        if (time.get() <= 0) {
            result.trySuccess(false);
            return;
        }

        long current = System.currentTimeMillis();
        AtomicReference<Timeout> futureRef = new AtomicReference<>();
        RFuture<RedissonCountDownLatchEntry> subscribeFuture = subscribe();
        subscribeFuture.onComplete((res, ex) -> {
            if (ex != null) {
                result.tryFailure(ex);
                return;
            }

            if (futureRef.get() != null) {
                futureRef.get().cancel();
            }

            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);

            await(time, result, subscribeFuture);
        });
    });
    return result;
}