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

es.moki.ratelimitj.redis.RedisRateLimiterFactory Maven / Gradle / Ivy

There is a newer version: 0.7.0
Show newest version
package es.moki.ratelimitj.redis;

import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.api.StatefulRedisConnection;
import es.moki.ratelimitj.core.limiter.request.AbstractRequestRateLimiterFactory;
import es.moki.ratelimitj.core.limiter.request.AsyncRequestRateLimiter;
import es.moki.ratelimitj.core.limiter.request.ReactiveRequestRateLimiter;
import es.moki.ratelimitj.core.limiter.request.RequestLimitRule;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;

import java.io.IOException;
import java.util.Set;

import static java.util.Objects.requireNonNull;

public class RedisRateLimiterFactory extends AbstractRequestRateLimiterFactory {

    private final RedisClient client;
    private StatefulRedisConnection connection;

    public RedisRateLimiterFactory(RedisClient client) {
        this.client = requireNonNull(client);
    }

    @Override
    public RequestRateLimiter getInstance(Set rules) {
        return lookupInstance(rules);
    }

    @Override
    public AsyncRequestRateLimiter getInstanceAsync(Set rules) {
        return lookupInstance(rules);
    }

    @Override
    public ReactiveRequestRateLimiter getInstanceReactive(Set rules) {
        return lookupInstance(rules);
    }

    protected RedisSlidingWindowRequestRateLimiter create(Set rules) {
        return new RedisSlidingWindowRequestRateLimiter(getConnection(), rules);
    }

    @Override
    public void close() throws IOException {
        client.shutdown();
    }

    private StatefulRedisConnection getConnection() {
        // going to ignore race conditions at the cost of having multiple connections
        if (connection == null) {
            connection = client.connect();
        }
        return connection;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy