Skip to content

Instantly share code, notes, and snippets.

@aldobongio
Created November 2, 2023 15:56
Show Gist options
  • Save aldobongio/dc81a29200eb0e92b63a9dc945e8868c to your computer and use it in GitHub Desktop.
Save aldobongio/dc81a29200eb0e92b63a9dc945e8868c to your computer and use it in GitHub Desktop.
bucket4j Jedis snippet
import java.time.Duration;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.BucketConfiguration;
import io.github.bucket4j.TokensInheritanceStrategy;
import io.github.bucket4j.redis.jedis.cas.JedisBasedProxyManager;
public class JedisSnippet {
private void test(JedisBasedProxyManager<byte[]> jedisBasedProxyManager) throws InterruptedException {
for (TokensInheritanceStrategy strategy : TokensInheritanceStrategy.values()) {
System.out.println("=========================");
System.out.println("Setting bandwith to 5/min");
// Bucket bucket = Bucket.builder().addLimit(limit -> limit.capacity(5).refillGreedy(5, Duration.ofMinutes(1))).build();
Bucket bucket = jedisBasedProxyManager.builder().build(strategy.name().getBytes(), () -> BucketConfiguration.builder()
.addLimit(limit -> limit.capacity(5).refillGreedy(5, Duration.ofMinutes(1))).build());
tryConsume(bucket, 5, true);
tryConsume(bucket, 1, false);
System.out.println("Update configuration to 10/min using strategy " + strategy);
BucketConfiguration newConfig = BucketConfiguration.builder()
.addLimit(limit -> limit.capacity(10).refillGreedy(10, Duration.ofMinutes(1))).build();
bucket.replaceConfiguration(newConfig, strategy);
System.out.println("Sleeping 60+ seconds in order to refill all tokens");
Thread.sleep(61000);
tryConsume(bucket, 10, true);
tryConsume(bucket, 1, false);
}
}
private void tryConsume(Bucket bucket, int count, boolean expectedOutcome) {
boolean outcome = bucket.tryConsume(count);
System.out.println("Attempt to consume " + count);
if (outcome != expectedOutcome) {
System.out.println("Unexpected outcome: was " + outcome + " but expecting " + expectedOutcome);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment