Search in sources :

Example 26 with CompletableFutureWrapper

use of org.redisson.misc.CompletableFutureWrapper in project redisson by redisson.

the class RedissonMap method putAllAsync.

@Override
public RFuture<Void> putAllAsync(Map<? extends K, ? extends V> map, int batchSize) {
    Map<K, V> batch = new HashMap<K, V>();
    AtomicInteger counter = new AtomicInteger();
    Iterator<Entry<K, V>> iter = ((Map<K, V>) map).entrySet().iterator();
    CompletionStage<Void> f = putAllAsync(batch, iter, counter, batchSize);
    return new CompletableFutureWrapper<>(f);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper)

Example 27 with CompletableFutureWrapper

use of org.redisson.misc.CompletableFutureWrapper in project redisson by redisson.

the class RedissonPermitExpirableSemaphore method tryAcquireAsync.

private RFuture<String> tryAcquireAsync(int permits, long waitTime, long ttl, TimeUnit timeUnit) {
    CompletableFuture<String> result = new CompletableFuture<>();
    AtomicLong time = new AtomicLong(timeUnit.toMillis(waitTime));
    long curr = System.currentTimeMillis();
    long timeoutDate = calcTimeout(ttl, timeUnit);
    RFuture<String> tryAcquireFuture = tryAcquireAsync(permits, timeoutDate);
    tryAcquireFuture.whenComplete((permitId, e) -> {
        if (e != null) {
            result.completeExceptionally(e);
            return;
        }
        if (permitId != null && !permitId.startsWith(":")) {
            if (!result.complete(permitId)) {
                releaseAsync(permitId);
            }
            return;
        }
        long el = System.currentTimeMillis() - curr;
        time.addAndGet(-el);
        if (time.get() <= 0) {
            result.complete(null);
            return;
        }
        long current = System.currentTimeMillis();
        AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
        CompletableFuture<RedissonLockEntry> subscribeFuture = subscribe();
        subscribeFuture.whenComplete((r, ex) -> {
            if (ex != null) {
                result.completeExceptionally(ex);
                return;
            }
            if (futureRef.get() != null) {
                futureRef.get().cancel();
            }
            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);
            tryAcquireAsync(time, permits, r, result, ttl, timeUnit);
        });
        if (!subscribeFuture.isDone()) {
            Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                @Override
                public void run(Timeout timeout) throws Exception {
                    if (!subscribeFuture.isDone()) {
                        result.complete(null);
                    }
                }
            }, time.get(), TimeUnit.MILLISECONDS);
            futureRef.set(scheduledFuture);
        }
    });
    return new CompletableFutureWrapper<>(result);
}
Also used : Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicLong(java.util.concurrent.atomic.AtomicLong) TimerTask(io.netty.util.TimerTask) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper)

Example 28 with CompletableFutureWrapper

use of org.redisson.misc.CompletableFutureWrapper in project redisson by redisson.

the class RedissonLock method tryLockAsync.

@Override
public RFuture<Boolean> tryLockAsync(long waitTime, long leaseTime, TimeUnit unit, long currentThreadId) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    AtomicLong time = new AtomicLong(unit.toMillis(waitTime));
    long currentTime = System.currentTimeMillis();
    RFuture<Long> ttlFuture = tryAcquireAsync(waitTime, leaseTime, unit, currentThreadId);
    ttlFuture.whenComplete((ttl, e) -> {
        if (e != null) {
            result.completeExceptionally(e);
            return;
        }
        // lock acquired
        if (ttl == null) {
            if (!result.complete(true)) {
                unlockAsync(currentThreadId);
            }
            return;
        }
        long el = System.currentTimeMillis() - currentTime;
        time.addAndGet(-el);
        if (time.get() <= 0) {
            trySuccessFalse(currentThreadId, result);
            return;
        }
        long current = System.currentTimeMillis();
        AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
        CompletableFuture<RedissonLockEntry> subscribeFuture = subscribe(currentThreadId);
        subscribeFuture.whenComplete((r, ex) -> {
            if (ex != null) {
                result.completeExceptionally(ex);
                return;
            }
            if (futureRef.get() != null) {
                futureRef.get().cancel();
            }
            long elapsed = System.currentTimeMillis() - current;
            time.addAndGet(-elapsed);
            tryLockAsync(time, waitTime, leaseTime, unit, r, result, currentThreadId);
        });
        if (!subscribeFuture.isDone()) {
            Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                @Override
                public void run(Timeout timeout) throws Exception {
                    if (!subscribeFuture.isDone()) {
                        subscribeFuture.cancel(false);
                        trySuccessFalse(currentThreadId, result);
                    }
                }
            }, time.get(), TimeUnit.MILLISECONDS);
            futureRef.set(scheduledFuture);
        }
    });
    return new CompletableFutureWrapper<>(result);
}
Also used : Timeout(io.netty.util.Timeout) AtomicReference(java.util.concurrent.atomic.AtomicReference) RedisException(org.redisson.client.RedisException) AtomicLong(java.util.concurrent.atomic.AtomicLong) TimerTask(io.netty.util.TimerTask) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 29 with CompletableFutureWrapper

use of org.redisson.misc.CompletableFutureWrapper in project redisson by redisson.

the class RedissonMapCache method scanIteratorAsync.

@Override
public RFuture<ScanResult<Map.Entry<Object, Object>>> scanIteratorAsync(String name, RedisClient client, long startPos, String pattern, int count) {
    List<Object> params = new ArrayList<Object>();
    params.add(System.currentTimeMillis());
    params.add(startPos);
    if (pattern != null) {
        params.add(pattern);
    }
    params.add(count);
    RFuture<MapCacheScanResult<Object, Object>> future = commandExecutor.evalReadAsync(client, name, codec, SCAN, "local result = {}; " + "local idleKeys = {}; " + "local res; " + "if (#ARGV == 4) then " + " res = redis.call('hscan', KEYS[1], ARGV[2], 'match', ARGV[3], 'count', ARGV[4]); " + "else " + " res = redis.call('hscan', KEYS[1], ARGV[2], 'count', ARGV[3]); " + "end;" + "local currentTime = tonumber(ARGV[1]); " + "for i, value in ipairs(res[2]) do " + "if i % 2 == 0 then " + "local key = res[2][i-1]; " + "local expireDate = 92233720368547758; " + "local expireDateScore = redis.call('zscore', KEYS[2], key); " + "if expireDateScore ~= false then " + "expireDate = tonumber(expireDateScore) " + "end; " + "local t, val = struct.unpack('dLc0', value); " + "if t ~= 0 then " + "local expireIdle = redis.call('zscore', KEYS[3], key); " + "if expireIdle ~= false then " + "if tonumber(expireIdle) > currentTime and expireDate > currentTime then " + "table.insert(idleKeys, key); " + "end; " + "expireDate = math.min(expireDate, tonumber(expireIdle)) " + "end; " + "end; " + "if expireDate > currentTime then " + "table.insert(result, key); " + "table.insert(result, val); " + "end; " + "end; " + "end;" + "return {res[1], result, idleKeys};", Arrays.asList(name, getTimeoutSetName(name), getIdleSetName(name)), params.toArray());
    CompletionStage<MapCacheScanResult<Object, Object>> f = future.thenApply(res -> {
        if (res.getIdleKeys().isEmpty()) {
            return res;
        }
        List<Object> args = new ArrayList<Object>(res.getIdleKeys().size() + 1);
        args.add(System.currentTimeMillis());
        encodeMapKeys(args, res.getIdleKeys());
        commandExecutor.evalWriteAsync(name, codec, new RedisCommand<Map<Object, Object>>("EVAL", new MapValueDecoder(new MapGetAllDecoder(args, 1))), // index is the first parameter
        "local currentTime = tonumber(table.remove(ARGV, 1)); " + "local map = redis.call('hmget', KEYS[1], unpack(ARGV)); " + "for i = #map, 1, -1 do " + "local value = map[i]; " + "if value ~= false then " + "local key = ARGV[i]; " + "local t, val = struct.unpack('dLc0', value); " + "if t ~= 0 then " + "local expireIdle = redis.call('zscore', KEYS[2], key); " + "if expireIdle ~= false then " + "if tonumber(expireIdle) > currentTime then " + "redis.call('zadd', KEYS[2], t + currentTime, key); " + "end; " + "end; " + "end; " + "end; " + "end; ", Arrays.asList(name, getIdleSetName(name)), args.toArray());
        return res;
    });
    return new CompletableFutureWrapper<>((CompletionStage<ScanResult<Map.Entry<Object, Object>>>) (Object) f);
}
Also used : CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) MapGetAllDecoder(org.redisson.connection.decoder.MapGetAllDecoder)

Example 30 with CompletableFutureWrapper

use of org.redisson.misc.CompletableFutureWrapper in project redisson by redisson.

the class RedissonLocalCachedMap method addAndGetOperationAsync.

@Override
protected RFuture<V> addAndGetOperationAsync(K key, Number value) {
    ByteBuf keyState = encodeMapKey(key);
    CacheKey cacheKey = localCacheView.toCacheKey(keyState);
    ByteBuf msg = encode(new LocalCachedMapInvalidate(instanceId, cacheKey.getKeyHash()));
    byte[] entryId = generateLogEntryId(cacheKey.getKeyHash());
    RFuture<V> future = commandExecutor.evalWriteAsync(getRawName(), 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(getRawName(), listener.getInvalidationTopicName(), listener.getUpdatesLogName()), keyState, new BigDecimal(value.toString()).toPlainString(), invalidateEntryOnChange, msg, System.currentTimeMillis(), entryId);
    CompletionStage<V> f = future.thenApply(res -> {
        if (res != null) {
            CacheKey cKey = localCacheView.toCacheKey(key);
            cachePut(cKey, key, res);
        }
        return res;
    });
    return new CompletableFutureWrapper<>(f);
}
Also used : NumberConvertor(org.redisson.client.protocol.convertor.NumberConvertor) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf) BigDecimal(java.math.BigDecimal)

Aggregations

CompletableFutureWrapper (org.redisson.misc.CompletableFutureWrapper)38 ByteBuf (io.netty.buffer.ByteBuf)16 AtomicLong (java.util.concurrent.atomic.AtomicLong)9 RFuture (org.redisson.api.RFuture)8 CompletableFuture (java.util.concurrent.CompletableFuture)7 StringCodec (org.redisson.client.codec.StringCodec)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 ByteBufUtil (io.netty.buffer.ByteBufUtil)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 CommandAsyncExecutor (org.redisson.command.CommandAsyncExecutor)5 Timeout (io.netty.util.Timeout)4 java.util.concurrent (java.util.concurrent)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 RSemaphore (org.redisson.api.RSemaphore)4 RTopic (org.redisson.api.RTopic)4 RedissonClient (org.redisson.api.RedissonClient)4 RedisCommand (org.redisson.client.protocol.RedisCommand)4 TimerTask (io.netty.util.TimerTask)3