bucket4j使用實例

本文主要演示一下bucket4j的幾個使用實例java

maven

<dependency>
            <groupId>com.github.vladimir-bukhtoyarov</groupId>
            <artifactId>bucket4j-core</artifactId>
            <version>4.0.1</version>
        </dependency>

rate limit

@Test
    public void testRateLimit(){
        // define the limit 1 time per 10 minute
        Bandwidth limit = Bandwidth.simple(1, Duration.ofMinutes(10));
        // construct the bucket
        Bucket bucket = Bucket4j.builder().addLimit(limit).build();
        IntStream.rangeClosed(1,5)
                .forEach(i -> {
                    executor.submit(() -> {
                        if(bucket.tryConsume(1)){
                            LOGGER.info("acquired");
                        }else{
                            LOGGER.info("blocked");
                        }
                    });
                });
    }
  • 這裏使用simple方法構造Bandwidth,進而構建bucket實例

scheduler

@Test
    public void testAsScheduler(){
        // define the limit 100 times per 1 minute
        Bandwidth limit = Bandwidth.simple(5, Duration.ofMinutes(1));
        // construct the bucket
        Bucket bucket = Bucket4j.builder().addLimit(limit).build();

        // do polling in infinite loop
        while (true) {
            // Consume a token from the token bucket.
            // If a token is not available this method will block until the refill adds one to the bucket.
            try {
                bucket.asScheduler().consume(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LOGGER.info("do remote call");
        }
    }

輸出實例git

23:14:46.740 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:14:46.744 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:14:46.744 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:14:46.744 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:14:46.744 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:14:58.749 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:15:10.749 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:15:22.754 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:15:34.757 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:15:46.759 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:15:58.762 [main] INFO com.example.demo.Bucket4jTest - do remote call
23:16:10.765 [main] INFO com.example.demo.Bucket4jTest - do remote call
  • 前面5個token消耗完以後,後續每隔12秒消耗一個token

小結

bucket4j類庫是一款優秀的java限流類庫,能夠用來限流,也能夠用做簡單調度。github

doc

相關文章
相關標籤/搜索