io.github.bucket4j.Bandwidth Java Examples

The following examples show how to use io.github.bucket4j.Bandwidth. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Bucket4jUsageUnitTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenBucketLimit_whenThrottleRequests_thenConsumeReturnsTrue() throws InterruptedException {
    Refill refill = Refill.intervally(1, Duration.ofSeconds(2));
    Bandwidth limit = Bandwidth.classic(1, refill);
    Bucket bucket = Bucket4j.builder()
        .addLimit(limit)
        .build();

    assertTrue(bucket.tryConsume(1));

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    CountDownLatch latch = new CountDownLatch(1);

    executor.schedule(new AssertTryConsume(bucket, latch), 2, TimeUnit.SECONDS);

    latch.await();
}
 
Example #2
Source File: LocalMemoryLimiter.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Response> isAllowed(String routeId, String id) {
    Config routeConfig = getConfig().get(routeId);
    if (routeConfig == null) {
        throw new IllegalArgumentException("No Configuration found for route " + routeId);
    }

    // How many requests per second do you want a user to be allowed to do?
    int replenishRate = routeConfig.getReplenishRate();
    // How much bursting do you want to allow?
    int burstCapacity = routeConfig.getBurstCapacity();

    Bucket bucket = this.buckets.computeIfAbsent(id, k -> {
        Refill refill = Refill.greedy(replenishRate, Duration.ofSeconds(1));
        Bandwidth limit = Bandwidth.classic(burstCapacity, refill);
        return Bucket4j.builder().addLimit(limit).build();
    });

    // tryConsume returns false immediately if no tokens available with the bucket
    ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(10);
    if (probe.isConsumed()) {
        // the limit is not exceeded
        return Mono.just(new Response(true, Collections.emptyMap()));
    } else {
        log.warn("request rate limited");
        // limit is exceeded
        return Mono.just(new Response(false, getHeaders(routeConfig, 0)));
    }
}
 
Example #3
Source File: BucketRateLimiter.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * @param capacity Capacity is the maximum number of tokens can be consumed.
 * @param tokensGeneratedInPeriod Tokens generated in period.
 * @param period Period that generating specific number of tokens.
 */
public BucketRateLimiter(long capacity, long tokensGeneratedInPeriod, Duration period) {
  Bandwidth bandwidth =
      Bandwidth.classic(capacity, Refill.greedy(tokensGeneratedInPeriod, period));
  this.bucket =
      Bucket4j.builder()
          .addLimit(bandwidth)
          .withSynchronizationStrategy(SynchronizationStrategy.SYNCHRONIZED)
          .build();
}
 
Example #4
Source File: Bucket4JBaseConfiguration.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private ConfigurationBuilder prepareBucket4jConfigurationBuilder(RateLimit rl) {
	ConfigurationBuilder configBuilder = Bucket4j.configurationBuilder();
	for (BandWidth bandWidth : rl.getBandwidths()) {
			Bandwidth bucket4jBandWidth = Bandwidth.simple(bandWidth.getCapacity(), Duration.of(bandWidth.getTime(), bandWidth.getUnit()));
			if(bandWidth.getFixedRefillInterval() > 0) {
				bucket4jBandWidth = Bandwidth.classic(bandWidth.getCapacity(), Refill.intervally(bandWidth.getCapacity(), Duration.of(bandWidth.getFixedRefillInterval(), bandWidth.getFixedRefillIntervalUnit())));
			}
			configBuilder = configBuilder.addLimit(bucket4jBandWidth);
	};
	return configBuilder;
}
 
Example #5
Source File: Bucket4jUsageUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenBucketLimit_whenExceedLimit_thenConsumeReturnsFalse() {
    Refill refill = Refill.intervally(10, Duration.ofMinutes(1));
    Bandwidth limit = Bandwidth.classic(10, refill);
    Bucket bucket = Bucket4j.builder()
        .addLimit(limit)
        .build();

    for (int i = 1; i <= 10; i++) {
        assertTrue(bucket.tryConsume(1));
    }
    assertFalse(bucket.tryConsume(1));
}
 
Example #6
Source File: Bucket4jUsageUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenMultipletLimits_whenExceedSmallerLimit_thenConsumeReturnsFalse() {
    Bucket bucket = Bucket4j.builder()
        .addLimit(Bandwidth.classic(10, Refill.intervally(10, Duration.ofMinutes(1))))
        .addLimit(Bandwidth.classic(5, Refill.intervally(5, Duration.ofSeconds(20))))
        .build();

    for (int i = 1; i <= 5; i++) {
        assertTrue(bucket.tryConsume(1));
    }
    assertFalse(bucket.tryConsume(1));
}
 
Example #7
Source File: LimitedGuild.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
public LimitedGuild(Bandwidth bandwidth) {
    this.limitedUsersMap = new ConcurrentHashMap<>();
    this.bandwidth = bandwidth;
}
 
Example #8
Source File: RateLimitByIpGatewayFilter.java    From microservice-integration with MIT License 4 votes vote down vote up
private Bucket createNewBucket() {
    Refill refill = Refill.of(refillTokens, refillDuration);
    Bandwidth limit = Bandwidth.classic(capacity, refill);
    return Bucket4j.builder().addLimit(limit).build();
}
 
Example #9
Source File: AbstractBucket4jRateLimiter.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 4 votes vote down vote up
private Supplier<BucketConfiguration> getBucketConfiguration(Long capacity, Duration period) {
    return () -> Bucket4j.configurationBuilder().addLimit(Bandwidth.simple(capacity, period)).build();
}
 
Example #10
Source File: BandwidthLimitTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testConstructor() {
    final BandwidthLimit bl1 = BandwidthLimit.of(100L, 1000L, 50L, Duration.ofSeconds(60L));
    assertThat(bl1.limit()).isEqualTo(100L);
    assertThat(bl1.overdraftLimit()).isEqualTo(1000L);
    assertThat(bl1.initialSize()).isEqualTo(50L);
    assertThat(bl1.period()).isEqualTo(Duration.ofSeconds(60L));
    assertThat(bl1.toSpecString()).isEqualTo("100;window=60;burst=1000");
    final Bandwidth b1 = bl1.bandwidth();
    assertThat(b1.getCapacity()).isEqualTo(1000L);
    assertThat(b1.getRefillTokens()).isEqualTo(100L);
    assertThat(b1.getInitialTokens()).isEqualTo(50L);
    assertThat(b1.getRefillPeriodNanos()).isEqualTo(Duration.ofSeconds(60L).toNanos());

    final BandwidthLimit bl2 = BandwidthLimit.of(100L, 1000L, Duration.ofSeconds(60L));
    assertThat(bl2.limit()).isEqualTo(100L);
    assertThat(bl2.overdraftLimit()).isEqualTo(1000L);
    assertThat(bl2.initialSize()).isEqualTo(0L);
    assertThat(bl2.period()).isEqualTo(Duration.ofSeconds(60L));
    assertThat(bl2.toSpecString()).isEqualTo("100;window=60;burst=1000");
    final Bandwidth b2 = bl2.bandwidth();
    assertThat(b2.getCapacity()).isEqualTo(1000L);
    assertThat(b2.getRefillTokens()).isEqualTo(100L);
    assertThat(b2.getInitialTokens()).isEqualTo(100L);
    assertThat(b2.getRefillPeriodNanos()).isEqualTo(Duration.ofSeconds(60L).toNanos());

    final BandwidthLimit bl3 = BandwidthLimit.of(100L, Duration.ofSeconds(60L));
    assertThat(bl3.limit()).isEqualTo(100L);
    assertThat(bl3.overdraftLimit()).isEqualTo(0L);
    assertThat(bl3.initialSize()).isEqualTo(0L);
    assertThat(bl3.period()).isEqualTo(Duration.ofSeconds(60L));
    assertThat(bl3.toSpecString()).isEqualTo("100;window=60");
    final Bandwidth b3 = bl3.bandwidth();
    assertThat(b3.getCapacity()).isEqualTo(100L);
    assertThat(b3.getRefillTokens()).isEqualTo(100L);
    assertThat(b3.getInitialTokens()).isEqualTo(100L);
    assertThat(b3.getRefillPeriodNanos()).isEqualTo(Duration.ofSeconds(60L).toNanos());

    final BandwidthLimit bl4 = BandwidthLimit.of(100L, 0L, Duration.ofSeconds(60L));
    assertThat(bl4.limit()).isEqualTo(100L);
    assertThat(bl4.overdraftLimit()).isEqualTo(0L);
    assertThat(bl4.initialSize()).isEqualTo(0L);
    assertThat(bl4.period()).isEqualTo(Duration.ofSeconds(60L));
    assertThat(bl4.toSpecString()).isEqualTo("100;window=60");
    final Bandwidth b4 = bl4.bandwidth();
    assertThat(b4.getCapacity()).isEqualTo(100L);
    assertThat(b4.getRefillTokens()).isEqualTo(100L);
    assertThat(b4.getInitialTokens()).isEqualTo(100L);
    assertThat(b4.getRefillPeriodNanos()).isEqualTo(Duration.ofSeconds(60L).toNanos());
}
 
Example #11
Source File: InfinispanJCacheTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void checkThatInfinispanProviderUnsupported() {
    Bucket4j.extension(JCache.class).builder().
            addLimit(Bandwidth.simple(10, Duration.ofSeconds(60))).
            build(cache, "42", RecoveryStrategy.RECONSTRUCT);
}
 
Example #12
Source File: PricingPlanService.java    From tutorials with MIT License 4 votes vote down vote up
private Bucket bucket(Bandwidth limit) {
    return Bucket4j.builder()
        .addLimit(limit)
        .build();
}
 
Example #13
Source File: RateLimiter.java    From Shadbot with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Specifies simple limitation {@code capacity} tokens per {@code period} time window.
 *
 * @param capacity Maximum amount of tokens.
 * @param period The period within tokens will be fully regenerated.
 */
public RateLimiter(int capacity, Duration period) {
    this(Bandwidth.classic(capacity, Refill.intervally(capacity, period)));
}
 
Example #14
Source File: RateLimiter.java    From Shadbot with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Specifies limitation with the provided bandwidth.
 *
 * @param bandwidth The bandwidth.
 */
public RateLimiter(Bandwidth bandwidth) {
    this.guildsLimitedMap = new ConcurrentHashMap<>();
    this.bandwidth = bandwidth;
}