-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRateLimiter.java
More file actions
41 lines (32 loc) · 1.26 KB
/
Copy pathRateLimiter.java
File metadata and controls
41 lines (32 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RateLimiter {
private final int maxRequestsPerSecond;
private final Map<String, UserRequestInfo> userRequests = new ConcurrentHashMap<>();
public RateLimiter(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public synchronized boolean allowRequest(String userId) {
long currentTime = System.currentTimeMillis();
userRequests.putIfAbsent(userId, new UserRequestInfo(currentTime, 0));
UserRequestInfo info = userRequests.get(userId);
// Reset counter if more than 1 second (1000ms) has passed
if (currentTime - info.lastResetTime > 1000) {
info.lastResetTime = currentTime;
info.requestCount = 0;
}
if (info.requestCount < maxRequestsPerSecond) {
info.requestCount++;
return true; // Request allowed
}
return false; // Rate limit exceeded!
}
private static class UserRequestInfo {
long lastResetTime;
int requestCount;
UserRequestInfo(long lastResetTime, int requestCount) {
this.lastResetTime = lastResetTime;
this.requestCount = requestCount;
}
}
}