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:
The project offers several features, some utilizing Spring's Expression Language for dynamic condition interpretation:
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:
[[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.
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
@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.
@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
org.springframework.boot
spring-boot-starter-aopto 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
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)
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
==== Filter Bucket4j 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,或尚未同步最近议题。