io.github.bucket4j.Bucket4j Java Examples

The following examples show how to use io.github.bucket4j.Bucket4j. 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: TokenBucketThrottlingStrategy.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new named strategy with specified {@link TokenBucket} configuration,
 * with minimum backoff period and with specific throttling headers scheme.
 *
 * @param tokenBucket {@link TokenBucket} configuration.
 * @param minimumBackoff optional {@link Duration} that defines a minimum backoff period
 *                       for throttled requests. By default, it will be set to 0 seconds.
 * @param headersScheme optional {@link ThrottlingHeaders} to define specific RateLimit Header Scheme
 *                      for HTTP. By default, no throttling headers will be used. The strategy will only use
 *                      standard HTTP Retry-After header.
 * @param sendQuota indicates whether to use quota header for the scheme.
 * @param name optional name of the strategy. By default, it will be assigned with a predefined name.
 */
TokenBucketThrottlingStrategy(TokenBucket tokenBucket,
                              @Nullable Duration minimumBackoff,
                              @Nullable ThrottlingHeaders headersScheme,
                              boolean sendQuota,
                              @Nullable String name) {
    super(name);
    // construct the bucket builder
    final LocalBucketBuilder builder = Bucket4j.builder().withNanosecondPrecision();
    for (BandwidthLimit limit : tokenBucket.limits()) {
        builder.addLimit(limit.bandwidth());
    }
    // build the bucket
    asyncBucket = builder.build().asAsync();
    minimumBackoffSeconds = (minimumBackoff == null) ? 0L : minimumBackoff.getSeconds();
    this.headersScheme = headersScheme;
    this.sendQuota = sendQuota;
    quota = sendQuota ? tokenBucket.toSpecString() : null;
}
 
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: 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 #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: InfinispanSerializerTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Test
public void tetsSerializationOfEntryProcessors() {
    BucketConfiguration configuration = Bucket4j.configurationBuilder()
            .addLimit(simple(10, ofSeconds(1)))
            .build();
    GridCommand command = new AddTokensCommand(42);

    testSerialization(new InitStateProcessor<>(configuration));
    testSerialization(new ExecuteProcessor<>(command));
    testSerialization(new InitStateAndExecuteProcessor(command, configuration));

    testSerialization(new SerializableFunctionAdapter<>(new ExecuteProcessor<>(command)));
}
 
Example #7
Source File: InfinispanSerializerTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    for (SerializationHandle<?> serializationHandle : Bucket4j.getSerializationHandles()) {
        String protoTypeId = "bucket4j.Bucket4jType_" + serializationHandle.getTypeId();
        serializerByClass.put(serializationHandle.getSerializedType(), new ProtobufMessageMarshaller<>(serializationHandle, protoTypeId));
    }
}
 
Example #8
Source File: Bucket4jProtobufContextInitializer.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public void registerMarshallers(SerializationContext serCtx) {
    for (SerializationHandle<?> serializationHandle : Bucket4j.getSerializationHandles()) {
        String protoTypeId = "bucket4j.Bucket4jType_" + serializationHandle.getTypeId();
        serCtx.registerMarshaller(new ProtobufMessageMarshaller<>(serializationHandle, protoTypeId));
    }
}
 
Example #9
Source File: Bucket4jProtobufContextInitializer.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Override
public void registerSchema(SerializationContext serCtx) {
    StringBuilder protoBuilder = new StringBuilder(FOOTER);

    for (SerializationHandle<?> serializationHandle : Bucket4j.getSerializationHandles()) {
        String typeName = "Bucket4jType_" + serializationHandle.getTypeId();
        String typeDefinition = TYPE_TEMPLATE.replace("[type_name]", typeName);
        protoBuilder.append(typeDefinition);
    }

    String generatedProtoFile = protoBuilder.toString();
    FileDescriptorSource protoSource = FileDescriptorSource.fromString(getProtoFileName(), generatedProtoFile);
    serCtx.registerProtoFiles(protoSource);
}
 
Example #10
Source File: HazelcastSerializerTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Test
public void tetsSerializationOfEntryProcessors() {
    BucketConfiguration configuration = Bucket4j.configurationBuilder()
            .addLimit(simple(10, ofSeconds(1)))
            .build();
    GridCommand command = new AddTokensCommand(42);

    testSerialization(new InitStateProcessor<>(configuration));
    testSerialization(new ExecuteProcessor<>(command));
    testSerialization(new InitStateAndExecuteProcessor(command, configuration));
}
 
Example #11
Source File: HazelcastSerializerTest.java    From bucket4j with Apache License 2.0 5 votes vote down vote up
@Test
public void tetsSerializationOfEntryProcessors() {
    BucketConfiguration configuration = Bucket4j.configurationBuilder()
            .addLimit(simple(10, ofSeconds(1)))
            .build();
    GridCommand command = new AddTokensCommand(42);

    testSerialization(new InitStateProcessor<>(configuration));
    testSerialization(new ExecuteProcessor<>(command));
    testSerialization(new InitStateAndExecuteProcessor(command, configuration));
}
 
Example #12
Source File: TokenBucketThrottlingStrategy.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Resets the Token-Bucket configuration at runtime by providing a new set of limits.
 * Empty set of limits will remove previously set limits. Reconfiguration will take place asynchronously.
 * @param tokenBucket Token-Bucket configuration
 * @return A {@link CompletableFuture} to handle asynchronous result
 */
public CompletableFuture<Void> reconfigure(TokenBucket tokenBucket) {
    // construct the configuration builder
    final ConfigurationBuilder builder = Bucket4j.configurationBuilder();
    for (BandwidthLimit limit : tokenBucket.limits()) {
        builder.addLimit(limit.bandwidth());
    }
    // reconfigure the bucket
    return asyncBucket.replaceConfiguration(builder.build())
                      .thenRun(() -> quota = sendQuota ? tokenBucket.toSpecString() : null);
}
 
Example #13
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 #14
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 #15
Source File: JCacheCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public ProxyManager<String>  resolve(String cacheName) {
	Cache springCache = cacheManager.getCache(cacheName);
	if (springCache == null) {
		throw new JCacheNotFoundException(cacheName);
	}

	return Bucket4j.extension(JCache.class).proxyManagerForCache(springCache);
}
 
Example #16
Source File: InfinispanJCacheCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public ProxyManager<String> resolve(String cacheName) {
	Cache<Object, Object> cache = cacheContainer.getCache(cacheName);
	if (cache == null) {
		throw new JCacheNotFoundException(cacheName);
	}

	FunctionalMapImpl functionalMap = FunctionalMapImpl.create(cache.getAdvancedCache());
	return Bucket4j.extension(Infinispan.class).proxyManagerForMap(ReadWriteMapImpl.create(functionalMap));
}
 
Example #17
Source File: HazelcastTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
protected ProxyManager<String> newProxyManager() {
    return Bucket4j.extension(getExtensionClass()).proxyManagerForMap(map);
}
 
Example #18
Source File: HazelcastTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@Override
public void testThatImpossibleToPassNullCacheToProxyManagerConstructor() {
    Bucket4j.extension(getExtensionClass()).proxyManagerForMap(null);
}
 
Example #19
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@Override
public void testThatImpossibleToPassNullCacheToProxyManagerConstructor() {
    Bucket4j.extension(getExtensionClass()).proxyManagerForMap(null);
}
 
Example #20
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
protected ProxyManager<String> newProxyManager() {
    return Bucket4j.extension(Infinispan.class).proxyManagerForMap(readWriteMap);
}
 
Example #21
Source File: HazelcastCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
public ProxyManager<String> resolve(String cacheName) {
	com.hazelcast.core.IMap<String, GridBucketState> map = hazelcastInstance.getMap(cacheName);
	return Bucket4j.extension(Hazelcast.class).proxyManagerForMap(map);
}
 
Example #22
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@Override
public void testThatImpossibleToPassNullCacheToProxyManagerConstructor() {
    Bucket4j.extension(getExtensionClass()).proxyManagerForMap(null);
}
 
Example #23
Source File: InfinispanTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
protected ProxyManager<String> newProxyManager() {
    return Bucket4j.extension(Infinispan.class).proxyManagerForMap(readWriteMap);
}
 
Example #24
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 #25
Source File: IgniteTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
@Override
public void testThatImpossibleToPassNullCacheToProxyManagerConstructor() {
    Bucket4j.extension(getExtensionClass()).proxyManagerForCache(null);
}
 
Example #26
Source File: IgniteTest.java    From bucket4j with Apache License 2.0 4 votes vote down vote up
@Override
protected ProxyManager<String> newProxyManager() {
    return Bucket4j.extension(getExtensionClass()).proxyManagerForCache(cache);
}
 
Example #27
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 #28
Source File: InfinispanCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
public ProxyManager<String> resolve(String cacheName) {
	Cache<Object, Object> cache = cacheContainer.getCache(cacheName);
	// TODO how to create an instance of ReadWriteMap
	return Bucket4j.extension(io.github.bucket4j.grid.infinispan.Infinispan.class).proxyManagerForMap(null);
}
 
Example #29
Source File: IgniteCacheResolver.java    From bucket4j-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
public ProxyManager<String> resolve(String cacheName) {
	org.apache.ignite.IgniteCache<String, GridBucketState> cache = ignite.cache(cacheName);
	return Bucket4j.extension(io.github.bucket4j.grid.ignite.Ignite.class).proxyManagerForCache(cache);
}
 
Example #30
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();
}