Ratelimiter-限流器的使用

RateLimiter

限流器的使用,一般用于接口qps或者某种资源的访问速率的限制

  1. 引入依赖

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>25.1-jre</version>
    </dependency>
    
  2. 代码实战,限制某个接口的qps为3

    public class RateLimiterDemo {
    
        //新建一个每秒限制3个的令牌桶
        public static RateLimiter rateLimiter = RateLimiter.create(3,1, TimeUnit.SECONDS);
        public static ExecutorService executor = Executors.newFixedThreadPool(10);
    
    
        public static void main(String[] args) {
            for (int i = 0; i < 10; i++) {
                executor.execute(() -> {
                    //获取令牌桶中一个令牌,最多等待10秒
                    if (rateLimiter.tryAcquire(1, 4, TimeUnit.SECONDS)) {
                        testInterface();
                        System.out.println(Thread.currentThread().getName()+" "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    }else {
                        System.out.println("请求频繁,限流住了");
                    }
                });
            }
        }
    
        public static void testInterface(){
            //to do
            //假设这个是上游接口,最大支持qps为3
            System.out.println("访问接口成功");
        }
    }
    
    

    结果:

image

参考:

  1. https://zhuanlan.zhihu.com/p/69986837
posted @ 2021-12-09 20:38  orangeScc  阅读(448)  评论(0编辑  收藏  举报