I know than a rate limiter with Bucket4J can be reconfigured dynamically, but can it be dynamically enabled/disabled?
In my case, if the configurations is 0 permits (per seconds), it means it's disabled. And internally I configure the bucket with a comically high limit rate.
You can see the code:
public void configure(int permitsPerSecond) {
if (permitsPerSecond > 0) {
// Enable rate limit with bucker4j
Refill refill = Refill.intervally(permitsPerSecond, Duration.ofSeconds(1L));
Bandwidth currentLimit = Bandwidth.classic(permitsPerSecond, refill);
BucketConfiguration currentConfiguration = BucketConfiguration.builder().
addLimit(currentLimit).
build();
bucket.replaceConfiguration(currentConfiguration, TokensInheritanceStrategy.RESET);
} else {
// Disable rate limit with ludicrous high rate
BucketConfiguration currentConfiguration = BucketConfiguration.builder().
addLimit(Bandwidth.simple(999_999_999_999L, Duration.ofSeconds(1))).
build();
bucket.replaceConfiguration(DEFAULT_CONFIGURATION,
TokensInheritanceStrategy.RESET);
}
}
public boolean allowExecution() {
return bucket.tryConsume(1L);
}
I tried searching documentation and code, expected a method like bucket.enable(boolean)
and bucket.getLimit().getCapacty()
, but no luck.
Is there another way I can disable dynamically the bucket? Also, can I access the current capacity of the bucket from the Bucket class?
Bucket4j does not provide direct ability to disable limits. So you need to find some trick that will behave approximately in desired way.
For example, you can reconfigure(via replaceConfiguration
) the bucket with extremely huge limit each time when you need to disable limit. Bellow is example of effectively infinite limit that is enough for usual cases:
BucketConfiguration infiniteConfiguration = BucketConfiguration.builder().
addLimit(Bandwidth.simple(Long.MAX_VALUE, Duration.ofNanos(Long.MAX_VALUE)).
build();
Then each time when you need to activate limits again, you should to reconfigure bucket again with regular configuration.