/
MyAsyncHandler.java
36 lines (31 loc) · 1.04 KB
/
MyAsyncHandler.java
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
package ratelimiter.example;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import ratelimiter.RateAsyncLimiter;
import ratelimiter.RateLimiterOptions;
import ratelimiter.inmemory.RateInMemoryAsyncLimiter;
class MyAsyncHandler {
private final RateLimiterOptions options = RateLimiterOptions.builder()
.max(5)
.duration(Duration.ofSeconds(10))
.build();
private final RateAsyncLimiter limiter = new RateInMemoryAsyncLimiter(options);
public CompletableFuture<Boolean> operation() {
return limiter.addAndGet("key", 1).thenApply(limit -> {
if (!limit.hasRemaining()) {
return false;
}
// all good
return true;
});
}
public static void main(String[] args)
throws ExecutionException, InterruptedException {
MyAsyncHandler handler = new MyAsyncHandler();
for (int i = 1; i <= 7; i++) {
Boolean result = handler.operation().get();
System.out.printf("%d: %s%n", i, result ? "OK" : "FAIL");
}
}
}