bucket4j使用实例

本文主要演示一下bucket4j的几个使用实例

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");
        }
    }

输出实例

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限流类库,可以用来限流,也可以用作简单调度。

doc

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值