package com.qmth.boot.redis.rateLimit;

import com.qmth.boot.core.rateLimit.service.RateLimiter;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RSemaphore;

public class RedisRateLimiter implements RateLimiter {

    private RRateLimiter limiter;

    private RSemaphore semaphore;

    public RedisRateLimiter(RRateLimiter limiter) {
        this.limiter = limiter;
    }

    public RedisRateLimiter(RSemaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public boolean acquire() {
        if (limiter != null) {
            return limiter.tryAcquire();
        } else if (semaphore != null) {
            return semaphore.tryAcquire();
        }
        return false;
    }

    @Override
    public void release() {
        if (semaphore != null) {
            semaphore.release();
        }
    }
}
