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

本文主要研究一下如何使用bucket4j-spring-boot-starter進行限流java

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

訪問/actuatorgit

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進行限流,適配了springboot一、springboot2以及zuul,經過配置文件配置便可輕鬆實現限流。github

doc

相關文章
相關標籤/搜索