All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.redisson.RedissonBaseAdder Maven / Gradle / Ivy

Go to download

Easy Redis Java client and Real-Time Data Platform. Valkey compatible. Sync/Async/RxJava3/Reactive API. Client side caching. Over 50 Redis based Java objects and services: JCache API, Apache Tomcat, Hibernate, Spring, Set, Multimap, SortedSet, Map, List, Queue, Deque, Semaphore, Lock, AtomicLong, Map Reduce, Bloom filter, Scheduler, RPC

There is a newer version: 3.40.2
Show newest version
/**
 * Copyright (c) 2013-2024 Nikita Koksharov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.redisson;

import org.redisson.api.RFuture;
import org.redisson.api.RSemaphore;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.connection.AdderEntry;
import org.redisson.misc.CompletableFutureWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author Nikita Koksharov
 *
 */
public abstract class RedissonBaseAdder extends RedissonExpirable {

    private static final Logger log = LoggerFactory.getLogger(RedissonBaseAdder.class);
    
    private static final String CLEAR_MSG = "0";
    private static final String SUM_MSG = "1";

    private final RedissonClient redisson;
    private final RTopic topic;
    private final int listenerId;
    
    public RedissonBaseAdder(CommandAsyncExecutor commandExecutor, String name, RedissonClient redisson) {
        super(commandExecutor, name);

        if (getSubscribeService().isShardingSupported()) {
            topic = RedissonShardedTopic.createRaw(StringCodec.INSTANCE, commandExecutor, suffixName(getRawName(), "adder-topic"));
        } else {
            topic = RedissonTopic.createRaw(StringCodec.INSTANCE, commandExecutor, suffixName(getRawName(), "adder-topic"));
        }

        this.redisson = redisson;

        AdderEntry entry = getServiceManager().getAddersUsage().computeIfAbsent(name, r -> new AdderEntry());
        entry.getUsage().incrementAndGet();

        listenerId = topic.addListener(String.class, (channel, msg) -> {
            String[] parts = msg.split(":");
            String id = parts[1];

            entry.getIds().add(id);

            if (parts[0].equals(SUM_MSG)) {
                RFuture addAndGetFuture = addAndGetAsync(id);
                addAndGetFuture.whenComplete((res, e) -> {
                    if (e != null) {
                        log.error("Can't increase sum", e);
                        return;
                    }

                    release(id, entry);
                });
            }

            if (parts[0].equals(CLEAR_MSG)) {
                doReset();

                release(id, entry);
            }
        });
    }

    private void release(String id, AdderEntry entry) {
        AtomicInteger counter = getServiceManager().getAddersCounter().computeIfAbsent(id, r -> new AtomicInteger());
        if (counter.incrementAndGet() == entry.getUsage().get()
                || entry.getUsage().get() == 0) {
            getServiceManager().getAddersCounter().remove(id);
            entry.getIds().remove(id);
            RSemaphore semaphore = getSemaphore(id);
            semaphore.releaseAsync().whenComplete((r, ex) -> {
                if (ex != null) {
                    log.error("Can't release semaphore", ex);
                }
            });
        }
    }

    protected abstract void doReset();

    public void reset() {
        get(resetAsync());
    }
    
    public void reset(long timeout, TimeUnit timeUnit) {
        get(resetAsync(timeout, timeUnit));
    }
    
    public RFuture sumAsync() {
        String id = getServiceManager().generateId();
        RSemaphore semaphore = getSemaphore(id);

        RFuture future = topic.publishAsync(SUM_MSG + ":" + id);
        CompletionStage f = future.thenCompose(r -> semaphore.acquireAsync(r.intValue()))
                                        .thenCompose(r -> getAndDeleteAsync(id))
                                        .thenCompose(r -> semaphore.deleteAsync().thenApply(res -> r));
        return new CompletableFutureWrapper<>(f);
    }

    private RSemaphore getSemaphore(String id) {
        return redisson.getSemaphore(suffixName(getRawName(), id + ":semaphore"));
    }

    protected String getCounterName(String id) {
        return suffixName(getRawName(), id + ":counter");
    }

    public RFuture sumAsync(long timeout, TimeUnit timeUnit) {
        String id = getServiceManager().generateId();
        RSemaphore semaphore = getSemaphore(id);

        RFuture future = topic.publishAsync(SUM_MSG + ":" + id);
        CompletionStage f = future.thenCompose(r -> {
                    return tryAcquire(semaphore, timeout, timeUnit, r.intValue());
                })
                                    .thenCompose(r -> getAndDeleteAsync(id))
                                    .thenCompose(r -> semaphore.deleteAsync().thenApply(res -> r));
        return new CompletableFutureWrapper<>(f);
    }

    protected CompletionStage tryAcquire(RSemaphore semaphore, long timeout, TimeUnit timeUnit, int value) {
        return semaphore.tryAcquireAsync(value, timeout, timeUnit).handle((res, e) -> {
            if (e != null) {
                throw new CompletionException(e);
            }
            
            if (res) {
                return null;
            }
            throw new CompletionException(new TimeoutException());
        });
    }

    public RFuture resetAsync() {
        String id = getServiceManager().generateId();
        RSemaphore semaphore = getSemaphore(id);

        RFuture future = topic.publishAsync(CLEAR_MSG + ":" + id);
        CompletionStage f = future.thenCompose(r -> semaphore.acquireAsync(r.intValue()))
                                        .thenCompose(r -> semaphore.deleteAsync().thenApply(res -> null));
        return new CompletableFutureWrapper<>(f);
    }
    
    public RFuture resetAsync(long timeout, TimeUnit timeUnit) {
        String id = getServiceManager().generateId();
        RSemaphore semaphore = getSemaphore(id);

        RFuture future = topic.publishAsync(CLEAR_MSG + ":" + id);
        CompletionStage f = future.thenCompose(r -> tryAcquire(semaphore, timeout, timeUnit, r.intValue()))
                                        .thenCompose(r -> semaphore.deleteAsync().thenApply(res -> null));
        return new CompletableFutureWrapper<>(f);
    }

    public void destroy() {
        topic.removeListener(listenerId);

        AdderEntry entry = getServiceManager().getAddersUsage().get(name);
        if (entry != null
                && entry.getUsage().decrementAndGet() == 0) {
            for (String id : entry.getIds()) {
                release(id, entry);
            }
            getServiceManager().getAddersUsage().remove(name, entry);
        }
    }

    protected abstract RFuture addAndGetAsync(String id);

    protected abstract RFuture getAndDeleteAsync(String id);

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy