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

com.founder.core.ratelimiter.TimeWindowRateLimiter Maven / Gradle / Ivy

package com.founder.core.ratelimiter;

import com.founder.core.model.LuaScript;
import com.founder.core.model.Result;
import com.founder.core.model.Rule;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.LongCodec;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.Collections;
import java.util.List;

import static com.founder.core.starter.RateLimiterAutoConfiguration.REDISSON_BEAN_NAME;

public class TimeWindowRateLimiter implements RateLimiter {

    private final RScript rScript;

    public TimeWindowRateLimiter(@Qualifier(REDISSON_BEAN_NAME) RedissonClient client) {
        this.rScript = client.getScript(LongCodec.INSTANCE);
    }

    @Override
    public Result isAllowed(Rule rule) {
        List keys = getKeys(rule.getKey());
        String script = LuaScript.getTimeWindowRateLimiterScript();
        List results = rScript.eval(RScript.Mode.READ_WRITE, script, RScript.ReturnType.MULTI, keys, rule.getRate(), rule.getRateInterval());
        boolean isAllowed = results.get(0) == 1L;
        long ttl = results.get(1);

        return new Result(isAllowed, ttl);
    }

    static List getKeys(String key) {
        String prefix = "request_rate_limiter.{" + key;
        String keys = prefix + "}";
        return Collections.singletonList(keys);
    }

}