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

com.github.lontime.shaded.org.redisson.RedissonIdGenerator Maven / Gradle / Ivy

The newest version!
/**
 * Copyright (c) 2013-2021 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 com.github.lontime.shaded.org.redisson;

import com.github.lontime.shaded.org.redisson.api.RFuture;
import com.github.lontime.shaded.org.redisson.api.RIdGenerator;
import com.github.lontime.shaded.org.redisson.client.codec.LongCodec;
import com.github.lontime.shaded.org.redisson.client.codec.StringCodec;
import com.github.lontime.shaded.org.redisson.client.protocol.RedisCommands;
import com.github.lontime.shaded.org.redisson.command.CommandAsyncExecutor;
import com.github.lontime.shaded.org.redisson.misc.CompletableFutureWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @author Nikita Koksharov
 *
 */
public class RedissonIdGenerator extends RedissonExpirable implements RIdGenerator {

    final Logger log = LoggerFactory.getLogger(getClass());

    RedissonIdGenerator(CommandAsyncExecutor connectionManager, String name) {
        super(connectionManager, name);
    }

    private String getAllocationSizeName() {
        return suffixName(getRawName(), "allocation");
    }

    @Override
    public boolean tryInit(long value, long allocationSize) {
        return get(tryInitAsync(value, allocationSize));
    }

    @Override
    public long nextId() {
        return get(nextIdAsync());
    }

    @Override
    public RFuture tryInitAsync(long value, long allocationSize) {
        return commandExecutor.evalWriteNoRetryAsync(getRawName(), StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                          "redis.call('setnx', KEYS[1], ARGV[1]); "
                        + "return redis.call('setnx', KEYS[2], ARGV[2]); ",
                Arrays.asList(getRawName(), getAllocationSizeName()), value, allocationSize);
    }

    private final AtomicLong start = new AtomicLong();
    private final AtomicLong counter = new AtomicLong();
    private final Queue> queue = new ConcurrentLinkedQueue<>();
    private final AtomicBoolean isWorkerActive = new AtomicBoolean();

    private void send() {
        if (!isWorkerActive.compareAndSet(false, true)
                || commandExecutor.getConnectionManager().getExecutor().isShutdown()) {
            return;
        }

        commandExecutor.getConnectionManager().getExecutor().execute(() -> {
            while (true) {
                if (queue.peek() == null) {
                    isWorkerActive.set(false);
                    if (!queue.isEmpty()) {
                        send();
                    }
                    break;
                }

                long v = counter.decrementAndGet();
                if (v >= 0) {
                    CompletableFuture pp = queue.poll();
                    pp.complete(start.incrementAndGet());
                } else {
                    try {
                        RFuture> future = commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_LIST,
                              "local allocationSize = redis.call('get', KEYS[2]); " +
                                    "if allocationSize == false then " +
                                        "allocationSize = 5000; " +
                                        "redis.call('set', KEYS[2], allocationSize);" +
                                    "end;" +
                                    "local value = redis.call('get', KEYS[1]); " +
                                    "if value == false then " +
                                        "redis.call('incr', KEYS[1]);" +
                                        "value = 1; " +
                                    "end; " +
                                    "redis.call('incrby', KEYS[1], allocationSize); " +
                                    "return {value, allocationSize}; ",
                            Arrays.asList(getRawName(), getAllocationSizeName()));
                        List res = get(future);

                        long value = (long) res.get(0);
                        long allocationSize = (long) res.get(1);
                        start.set(value);
                        counter.set(allocationSize);

                        CompletableFuture pp = queue.poll();
                        counter.decrementAndGet();
                        pp.complete(start.get());
                    } catch (Exception e) {
                        if (e instanceof RedissonShutdownException) {
                            break;
                        }

                        log.error(e.getMessage(), e);

                        isWorkerActive.set(false);
                        send();
                        break;
                    }
                }
            }
        });
    }

    @Override
    public RFuture nextIdAsync() {
        CompletableFuture promise = new CompletableFuture<>();
        queue.add(promise);
        send();
        return new CompletableFutureWrapper<>(promise);
    }

    @Override
    public RFuture deleteAsync() {
        return deleteAsync(getRawName(), getAllocationSizeName());
    }

    @Override
    public RFuture sizeInMemoryAsync() {
        return super.sizeInMemoryAsync(Arrays.asList(getRawName(), getAllocationSizeName()));
    }

    @Override
    public RFuture expireAsync(long timeToLive, TimeUnit timeUnit, String param, String... keys) {
        return super.expireAsync(timeToLive, timeUnit, param, getRawName(), getAllocationSizeName());
    }

    @Override
    protected RFuture expireAtAsync(long timestamp, String param, String... keys) {
        return super.expireAtAsync(timestamp, param, getRawName(), getAllocationSizeName());
    }

    @Override
    public RFuture clearExpireAsync() {
        return clearExpireAsync(getRawName(), getAllocationSizeName());
    }

}