use of io.github.bucket4j.Refill in project api-framework by vinscom.
the class RateLimiterProcessor method process.
@Override
public Single<BridgeEventContext> process(Single<BridgeEventContext> pContext) {
return pContext.map((ctx) -> {
if (ctx.getBridgeEvent().failed() || !isEnable()) {
return ctx;
}
BridgeEventType eventType = ctx.getBridgeEvent().type();
Bucket bucket = getCache().get(eventType).get(ctx.getBridgeEvent().socket().writeHandlerID(), () -> {
Refill refill = Refill.smooth(getRateOfTokenFill().getOrDefault(eventType, getDefaultRateOfTokenFill()), Duration.ofSeconds(getRateOfTokenFillDuration().getOrDefault(eventType, getDefaultRateOfTokenFillDuration())));
Bandwidth limit = Bandwidth.classic(getTokenBucketSize().getOrDefault(eventType, getDefaultTokenBucketSize()), refill);
return Bucket4j.builder().addLimit(limit).build();
});
if (!bucket.tryConsume(1)) {
getLog().debug(() -> String.format("[%s] Rate limit crossed for connection:[%s],event:[%s]", ctx.getId(), ctx.getBridgeEvent().socket().writeHandlerID(), eventType.toString()));
ctx.getBridgeEvent().fail("Rate Limit Crossed");
}
return ctx;
});
}
Aggregations