Search in sources :

Example 31 with CompletableFutureWrapper

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

the class RedissonLocalCachedMap method fastPutIfAbsentAsync.

@Override
public RFuture<Boolean> fastPutIfAbsentAsync(K key, V value) {
    if (storeMode == LocalCachedMapOptions.StoreMode.LOCALCACHE) {
        ByteBuf mapKey = encodeMapKey(key);
        CacheKey cacheKey = localCacheView.toCacheKey(mapKey);
        CacheValue prevValue = cachePutIfAbsent(cacheKey, key, value);
        if (prevValue == null) {
            broadcastLocalCacheStore(value, mapKey, cacheKey);
            return new CompletableFutureWrapper<>(true);
        } else {
            mapKey.release();
            return new CompletableFutureWrapper<>(false);
        }
    }
    RFuture<Boolean> future = super.fastPutIfAbsentAsync(key, value);
    CompletionStage<Boolean> f = future.thenApply(res -> {
        if (res) {
            CacheKey cacheKey = localCacheView.toCacheKey(key);
            cachePut(cacheKey, key, value);
        }
        return res;
    });
    return new CompletableFutureWrapper<>(f);
}
Also used : CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf)

Example 32 with CompletableFutureWrapper

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

the class RedissonLocalCachedMap method putOperationAsync.

@Override
protected RFuture<V> putOperationAsync(K key, V value) {
    ByteBuf mapKey = encodeMapKey(key);
    CacheKey cacheKey = localCacheView.toCacheKey(mapKey);
    CacheValue prevValue = cachePut(cacheKey, key, value);
    broadcastLocalCacheStore(value, mapKey, cacheKey);
    if (storeMode == LocalCachedMapOptions.StoreMode.LOCALCACHE) {
        V val = null;
        if (prevValue != null) {
            val = (V) prevValue.getValue();
        }
        return new CompletableFutureWrapper<>(val);
    }
    ByteBuf mapValue = encodeMapValue(value);
    byte[] entryId = generateLogEntryId(cacheKey.getKeyHash());
    ByteBuf msg = createSyncMessage(mapKey, mapValue, cacheKey);
    return commandExecutor.evalWriteAsync(getRawName(), codec, RedisCommands.EVAL_MAP_VALUE, "local v = redis.call('hget', KEYS[1], ARGV[1]); " + "redis.call('hset', KEYS[1], ARGV[1], ARGV[2]); " + "if ARGV[4] == '1' then " + "redis.call('publish', KEYS[2], ARGV[3]); " + "end;" + "if ARGV[4] == '2' then " + "redis.call('zadd', KEYS[3], ARGV[5], ARGV[6]);" + "redis.call('publish', KEYS[2], ARGV[3]); " + "end;" + "return v; ", Arrays.<Object>asList(getRawName(), listener.getInvalidationTopicName(), listener.getUpdatesLogName()), mapKey, mapValue, msg, invalidateEntryOnChange, System.currentTimeMillis(), entryId);
}
Also used : CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf)

Example 33 with CompletableFutureWrapper

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

the class RedissonLocalCachedMap method putAllOperationAsync.

@Override
protected RFuture<Void> putAllOperationAsync(Map<? extends K, ? extends V> map) {
    if (storeMode == LocalCachedMapOptions.StoreMode.LOCALCACHE) {
        for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
            ByteBuf keyEncoded = encodeMapKey(entry.getKey());
            CacheKey cacheKey = localCacheView.toCacheKey(keyEncoded);
            cachePut(cacheKey, entry.getKey(), entry.getValue());
            broadcastLocalCacheStore(entry.getValue(), keyEncoded, cacheKey);
        }
        return new CompletableFutureWrapper((Void) null);
    }
    List<Object> params = new ArrayList<Object>(map.size() * 3);
    params.add(invalidateEntryOnChange);
    params.add(map.size() * 2);
    byte[][] hashes = new byte[map.size()][];
    int i = 0;
    for (java.util.Map.Entry<? extends K, ? extends V> t : map.entrySet()) {
        ByteBuf mapKey = encodeMapKey(t.getKey());
        ByteBuf mapValue = encodeMapValue(t.getValue());
        params.add(mapKey);
        params.add(mapValue);
        CacheKey cacheKey = localCacheView.toCacheKey(mapKey);
        hashes[i] = cacheKey.getKeyHash();
        i++;
    }
    ByteBuf msgEncoded = null;
    if (syncStrategy == SyncStrategy.UPDATE) {
        List<LocalCachedMapUpdate.Entry> entries = new ArrayList<LocalCachedMapUpdate.Entry>();
        for (int j = 2; j < params.size(); j += 2) {
            ByteBuf key = (ByteBuf) params.get(j);
            ByteBuf value = (ByteBuf) params.get(j + 1);
            entries.add(new LocalCachedMapUpdate.Entry(key, value));
        }
        msgEncoded = encode(new LocalCachedMapUpdate(instanceId, entries));
    } else if (syncStrategy == SyncStrategy.INVALIDATE) {
        msgEncoded = encode(new LocalCachedMapInvalidate(instanceId, hashes));
    }
    if (invalidateEntryOnChange == 2) {
        long time = System.currentTimeMillis();
        for (byte[] hash : hashes) {
            byte[] entryId = generateLogEntryId(hash);
            params.add(time);
            params.add(entryId);
        }
    }
    if (msgEncoded != null) {
        params.add(msgEncoded);
    }
    RFuture<Void> future = commandExecutor.evalWriteAsync(getRawName(), codec, RedisCommands.EVAL_VOID, "for i=3, tonumber(ARGV[2]) + 2, 5000 do " + "redis.call('hmset', KEYS[1], unpack(ARGV, i, math.min(i+4999, tonumber(ARGV[2]) + 2))); " + "end; " + "if ARGV[1] == '1' then " + "redis.call('publish', KEYS[2], ARGV[#ARGV]); " + "end;" + "if ARGV[1] == '2' then " + "for i=tonumber(ARGV[2]) + 2 + 1, #ARGV - 1, 5000 do " + "redis.call('zadd', KEYS[3], unpack(ARGV, i, math.min(i+4999, #ARGV - 1))); " + "end; " + "redis.call('publish', KEYS[2], ARGV[#ARGV]); " + "end;", Arrays.asList(getRawName(), listener.getInvalidationTopicName(), listener.getUpdatesLogName()), params.toArray());
    CompletionStage<Void> f = future.thenApply(res -> {
        cacheMap(map);
        return null;
    });
    return new CompletableFutureWrapper<>(f);
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) RLocalCachedMap(org.redisson.api.RLocalCachedMap)

Example 34 with CompletableFutureWrapper

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

the class RedissonSemaphore method tryAcquireAsync.

@Override
public RFuture<Boolean> tryAcquireAsync(int permits, long waitTime, TimeUnit unit) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    AtomicLong time = new AtomicLong(unit.toMillis(waitTime));
    long curr = System.currentTimeMillis();
    RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits);
    tryAcquireFuture.whenComplete((res, e) -> {
        if (e != null) {
            result.completeExceptionally(e);
            return;
        }
        if (res) {
            if (!result.complete(true)) {
                releaseAsync(permits);
            }
            return;
        }
        long elap = System.currentTimeMillis() - curr;
        time.addAndGet(-elap);
        if (time.get() <= 0) {
            result.complete(false);
            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);
            if (time.get() < 0) {
                unsubscribe(r);
                result.complete(false);
                return;
            }
            tryAcquireAsync(time, permits, r, result);
        });
        if (!subscribeFuture.isDone()) {
            Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {

                @Override
                public void run(Timeout timeout) throws Exception {
                    if (!subscribeFuture.isDone()) {
                        result.complete(false);
                    }
                }
            }, 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 35 with CompletableFutureWrapper

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

the class RedissonLocalCachedMap method replaceAsync.

@Override
public RFuture<Boolean> replaceAsync(K key, V oldValue, V newValue) {
    if (storeMode == LocalCachedMapOptions.StoreMode.LOCALCACHE) {
        ByteBuf mapKey = encodeMapKey(key);
        CacheKey cacheKey = localCacheView.toCacheKey(mapKey);
        if (cacheReplace(cacheKey, key, oldValue, newValue)) {
            broadcastLocalCacheStore(newValue, mapKey, cacheKey);
            return new CompletableFutureWrapper<>(true);
        } else {
            mapKey.release();
            return new CompletableFutureWrapper<>(false);
        }
    }
    RFuture<Boolean> future = super.replaceAsync(key, oldValue, newValue);
    CompletionStage<Boolean> f = future.thenApply(res -> {
        if (res) {
            CacheKey cacheKey = localCacheView.toCacheKey(key);
            cachePut(cacheKey, key, newValue);
        }
        return res;
    });
    return new CompletableFutureWrapper<>(f);
}
Also used : CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) ByteBuf(io.netty.buffer.ByteBuf)

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