[case35]bucket4j-spring-boot-starter小试牛刀

10次阅读

共计 2119 个字符,预计需要花费 6 分钟才能阅读完成。


本文主要研究一下如何使用 bucket4j-spring-boot-starter 进行限流
maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>jcache</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
<artifactId>bucket4j-spring-boot-starter</artifactId>
<version>0.1.3</version>
</dependency>
<dependency>
<groupId>com.github.vladimir-bukhtoyarov</groupId>
<artifactId>bucket4j-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.github.vladimir-bukhtoyarov</groupId>
<artifactId>bucket4j-jcache</artifactId>
<version>4.0.0</version>
</dependency>
配置
开启缓存
@Bean
public CacheManager cacheManager() {
final CachingProvider cachingProvider = Caching.getCachingProvider();
return cachingProvider.getCacheManager();
}
application.yml
management:
endpoints:
web:
exposure:
include: “*”
spring:
cache:
cache-names:
– buckets
caffeine:
spec: maximumSize=1000000,expireAfterAccess=3600s
bucket4j:
enabled: true
filters:
– cache-name: buckets
filter-method: servlet
url: /*
rate-limits:
– bandwidths:
– capacity: 5
time: 1
unit: seconds

这里设置了名为 buckets 的缓存,过期时间为 1h,容量为 1000000
设置的 rate-limits 每 10 秒 5 个 token

验证
wrk -t12 -c20 -d10s -T60s –latency http://localhost:8080/actuator
访问 /actuator
curl -i http://localhost:8080/actuator
HTTP/1.1 429
X-Rate-Limit-Retry-After-Seconds: 0
Content-Type: application/json;charset=ISO-8859-1
Content-Length: 35
Date: Sun, 02 Sep 2018 08:03:51 GMT

{“message”: “Too many requests!”}
小结
bucket4j-spring-boot-starter 使用 bucket4j 进行限流,适配了 springboot1、springboot2 以及 zuul,通过配置文件配置即可轻松实现限流。
doc

bucket4j-spring-boot-starter
bucket4j-spring-boot-starter-examples

正文完
 0