Search in sources :

Example 1 with Refill

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;
    });
}
Also used : Bucket(io.github.bucket4j.Bucket) Bandwidth(io.github.bucket4j.Bandwidth) Refill(io.github.bucket4j.Refill) BridgeEventType(io.vertx.ext.bridge.BridgeEventType)

Aggregations

Bandwidth (io.github.bucket4j.Bandwidth)1 Bucket (io.github.bucket4j.Bucket)1 Refill (io.github.bucket4j.Refill)1 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)1