百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
B

bucket4j-spring-boot-starter

> 后端框架
开源

Bucket4j Spring Boot 启动器

367 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Bucket4j Spring Boot 启动器

:url-repo: https://github.com/MarcGiffing/bucket4j-spring-boot-starter :url: https://github.com/MarcGiffing/bucket4j-spring-boot-starter/tree/master :url-examples: {url}/examples :url-config-cache: {url}/cache/

image:{url-repo}/actions/workflows/maven.yml/badge.svg[Build Status,link={url-repo}/actions/workflows/maven.yml] image:{url-repo}/actions/workflows/codeql.yml/badge.svg[Build Status,link={url-repo}/actions/workflows/codeql.yml] image:{url-repo}/actions/workflows/pmd.yml/badge.svg[Build Status,link={url-repo}/actions/workflows/pmd.yml]

Project version overview:

  • 0.20.0 - Bucket4j 8.16.x - Spring Boot 4.0.0 - Restructure Maven Modules. See >

  • 0.14.0 - Bucket4j 8.15.x - Spring Boot 4.0.0 - Spring Gateway Support dropped

  • 0.13.0 - Bucket4j 8.14.x - Spring Boot 3.5.x - Bucket4j Deps have _jdk17 in the artifactId

  • 0.12.9 - Bucket4j 8.10.x - Spring Boot 3.4.x

  • 0.12.8 - Bucket4j 8.10.x - Spring Boot 3.3.x

  • <> ** <> ** <>

  • <> ** <> *** > *** > *** > *** > *** <>

  • ** > ** >

  • <> ** > ** > ** > ** <>

[[introduction]] == Spring Boot Starter for Bucket4j

This project is a Spring Boot Starter for Bucket4j, allowing you to set access limits on your API effortlessly. Its key advantage lies in the configuration via properties or yaml files, eliminating the need for manual code authoring.

Here are some example use cases:

  • Preventing DoS Attacks
  • Thwarting brute-force login attempts
  • Implementing request throttling for specific regions, unauthenticated users, and authenticated users
  • Applying rate limits for non-paying users or users with varying permissions

The project offers several features, some utilizing Spring's Expression Language for dynamic condition interpretation:

  • Cache key for differentiate the by username, IP address, ...)
  • Execution based on specific conditions
  • Skipping based on specific conditions
  • Post-token consumption actions based on filter/method results

You have two options for rate limit configuration: adding a filter for incoming web requests or applying fine-grained control at the method level.

[[introduction_filter]] === Use Filter for rate limiting

Filters are customizable components designed to intercept incoming web requests, capable of rejecting requests to halt further processing. You can incorporate multiple filters for various URLs or opt to bypass rate limits entirely for authenticated users. When the limit is exceeded, the web request is aborted, and the client receives an HTTP Status 429 Too Many Requests error.

This projects supports the following filters:

  • https://docs.oracle.com/javaee%2F6%2Fapi%2F%2F/javax/servlet/Filter.html[Servlet Filter] (Default)
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/server/WebFilter.html[Webflux Webfilter] (reactive)
  • https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway/global-filters.html[Spring Cloud Gateway Global Filter] (reactive)

[source,properties]

bucket4j.filters[0].cache-name=buckets # the name of the cache bucket4j.filters[0].url=^(/hello).* # regular expression for the url bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=5 # refills 5 tokens every 10 seconds (interval) bucket4j.filters[0].rate-limits[0].bandwidths[0].time=10 bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=seconds bucket4j.filters[0].rate-limits[0].bandwidths[0].refill-speed=interval

[[introduction_method]] === Use Annotations on methods for rate limiting

Utilizing the '@RateLimiting' annotation, AOP intercepts your method. This grants you comprehensive access to method parameters, empowering you to define the rate limit key or conditionally skip rate limiting with ease.

==== Method Configuration

Bucket configuration is done in application.properties or application.yaml.

.application.properties [source,properties]

bucket4j.methods[0].name=not_an_admin # the name of the configuration for annotation reference bucket4j.methods[0].cache-name=buckets # the name of the cache bucket4j.methods[0].rate-limits[0].bandwidths[0].capacity=5 # refills 5 tokens every 10 seconds (intervall) bucket4j.methods[0].rate-limits[0].bandwidths[0].time=10 bucket4j.methods[0].rate-limits[0].bandwidths[0].unit=seconds bucket4j.methods[0].rate-limits[0].bandwidths[0].refill-speed=intervall bucket4j.default-method-metric-tags[0].key=IP bucket4j.default-method-metric-tags[0].expression="@testServiceImpl.getRemoteAddr()" # reference to a bean method to fill the metric key bucket4j.default-method-metric-tags[0].types[0]=REJECTED_COUNTER bucket4j.default-method-metric-tags[0].types[1]=CONSUMED_COUNTER bucket4j.default-method-metric-tags[0].types[2]=PARKED_COUNTER bucket4j.default-method-metric-tags[0].types[3]=INTERRUPTED_COUNTER bucket4j.default-method-metric-tags[0].types[4]=DELAYED_COUNTER

.application.yaml [source,yaml]

bucket4j: methods: - name: not_an_admin # the name of the configuration for annotation reference cache-name: buckets # the name of the cache rate-limit: bandwidths: - capacity: 5 # refills 5 tokens every 10 seconds (intervall) time: 30 unit: seconds refill-speed: interval default-method-metric-tags: - key: IP expression: "@testServiceImpl.getRemoteAddr()" # reference to a bean method to fill the metric key types: - REJECTED_COUNTER - CONSUMED_COUNTER - PARKED_COUNTER - INTERRUPTED_COUNTER - DELAYED_COUNTER


The in this example configuration referenced testServiceImpl is not part of bucket4j-spring-boot-starter. If you would like to have the IP as metric tag you need to implement you own mechanism for that.

Working example for method annotation and IPs in metrics: {url-examples}/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/example/jedis-redis[jedis-redis Example project]

==== Method annotation

[source,java]

@RateLimiting( // reference to the property file name = "not_an_admin", // the rate limit is per user cacheKey= "#username", // only when the parameter is not admin executeCondition = "#username != 'admin'", // skip when parameter equals admin skipCondition = "#username eq 'admin", // the method name is added to the cache key to prevent conflicts with other methods ratePerMethod = true, // if the limit is exceeded the fallback method is called. If not provided an exception is thrown fallbackMethodName = "myFallbackMethod") public String execute(String username) { log.info("Method with Param {} executed", username); return myParamName; }

// the fallback method must have the same signature
public String myFallbackMethod(String username) {
    log.info("Fallback-Method with Param {} executed", username);
    return myParamName;
}

The '@RateLimiting' annotation on class level executes the rate limit on all public methods of the class. With '@IgnoreRateLimiting' you can ignore the rate limit at all on class level or for specific method on method level.

[source,java]

@Component @Slf4j @RateLimiting(name = "default") public class TestService {

public void notAnnotatedMethod() {
    log.info("Method notAnnotatedMethod");
}

@IgnoreRateLimiting
public void ignoreMethod() {
    log.info("Method ignoreMethod");
}

}

==== Method dependencies

As the @RateLimiting mechanism uses AOP you need to ensure your spring-boot provides the necessary dependencies.

Just add

[source,xml]

org.springframework.boot
spring-boot-starter-aop

to your project.

You can find some Configuration examples in the test project: {url-examples}/general-tests/src/main/java/com/giffing/bucket4j/spring/boot/starter/general/tests/method[Examples]

[[project_configuration]] == Project Configuration

[[bucket4j_complete_properties]] === General Bucket4j properties

[source,properties]

bucket4j.enabled=true # enable/disable bucket4j support bucket4j.cache-to-use= # If you use multiple caching implementation in your project and you want to choose a specific one you can set the cache here (jcache, hazelcast, ignite, redis)

Default Properties which can be overiden for the filters

bucket4j.default-http-content-type=application/json bucket4j.default-http-status-code=TOO_MANY_REQUESTS # Enum value of org.springframework.http.HttpStatus bucket4j.default-http-response-body={ "message": "Too many requests!" } # the json response which should be added to the body

Optional default metric tags for all filters

bucket4j.default-metric-tags[0].key=IP bucket4j.default-metric-tags[0].expression=getRemoteAddr() bucket4j.default-metric-tags[0].types=REJECTED_COUNTER

==== Filter Bucket4j properties

[source,properties]

bucket4j.filter-config-caching-enabled=true #Enable/disable caching of filter configurations. bucket4j.filter-config-cache-name=filterConfigCache #The name of the cache where the configurations are stored. Defaults to 'filterConfigCache'. bucket4j.filters[0].id=filter1 # The id of the filter. This field is mandatory when configuration caching is enabled and should always be a unique string. bucket4j.filters[0].major-version=1 # [min = 1, max = 92 million] Major version number of the configuration. bucket4j.filters[0].minor-version=1 # [min = 1, max = 99 billion] Minor version number of the configuration. (intended for internal updates, for example based on CPU-usage, but can also be used for regular updates) bucket4j.filters[0].cache-name=buckets # the name of the cache key bucket4j.filters[0].filter-method=servlet # [servlet,webflux,gateway] bucket4j.filters[0].filter-order= # Per default the lowest integer plus 10. Set it to a number higher then zero to execute it after e.g. Spring Security. bucket4j.filters[0].http-content-type=application/json bucket4j.filters[0].http-status-code=TOO_MANY_REQUESTS # Enum value of org.springframework.http.HttpStatus bucket4j.filters[0].http-response-body={ "message": "Too many requests" } # the json response which should be added to the body bucket4j.filters[0].http-response-headers.=MY_CUSTOM_HEADER_VALUE # You can add any numbers of custom headers bucket4j.filters[0].hide-http-response-headers=true # Hides response headers like x-rate-limit-remaining or x-rate-limit-retry-after-seconds on rate limiting bucket4j.filters[0].url=.* # a regular expression bucket4j.filters[0].strategy=first # [first, all] if multiple rate limits configured the 'first' strategy stops the processing after the first matching bucket4j.filters[0].rate-limits[0].cache-key=getRemoteAddr() # defines the cache key. It will be evaluated with the Spring Expression Language bucket4j.filters[0].rate-limits[0].num-tokens=1 # The number of tokens to consume bucket4j.filters[0].rate-limits[0].execute-condition=1==1 # an optional SpEl expression to decide to execute the rate limit or not bucket4j.filters[1].rate-limits[0].post-execute-condition= # an optional SpEl expression to decide if the token consumption should only estimated for the incoming request and the returning response used to check if the token must be consumed: getStatus() eq 401 bucket4j.filters[0].rate-limits[0].execute-predicates[0]=PATH=/hello,/world # On the HTTP Path as a list bucket4j.filters[0].rate-limits[0].execute-predicates[1]=METHOD=GET,POST # On the HTTP Method bucket4j.filters[0].rate-limits[0].execute-predicates[2]=QUERY=HELLO # Checks for the existence of a Query Parameter bucket4j.filters[0].rate-limits[0].skip-condition=1==1 # an optional SpEl expression to skip the rate limit bucket4j.filters[0].rate-limits[0].tokens-inheritance-strategy=RESET # [RESET, AS_IS, ADDITIVE, PROPORTIONALLY], defaults to RESET and is only used for dynamically updating configurations bucket4j.filters[0].rate-limits[0].bandwidths

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Javabucket4jjavarate-limitspring

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架