com.infusers.core.ratelimit.RateLimitingService Maven / Gradle / Ivy
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 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 = "rate-limit:" + 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