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

com.infusers.core.ratelimit.RateLimitingService Maven / Gradle / Ivy

There is a newer version: 2024.12.0008
Show newest version
package com.infusers.core.ratelimit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.infusers.core.cache.redis.RedisCacheKeys;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Service
public class RateLimitingService {
    private final StringRedisTemplate redisTemplate;

    @Autowired
    public RateLimitingService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean isAllowed(String key, int maxRequests, Duration timeWindow) {
        String redisKey = RedisCacheKeys.RATE_LIMIT_PREFIX_KEY + key;
        Long currentCount = redisTemplate.opsForValue().increment(redisKey);
        if (currentCount == 1) {
            redisTemplate.expire(redisKey, timeWindow.getSeconds(), TimeUnit.SECONDS);
        }
        return currentCount <= maxRequests;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy