zoukankan      html  css  js  c++  java
  • Guava的RateLimiter在单机限流中的正确用法

    错误使用

    在实现限流时,网上的各种文章基本都会提到Guava的RateLimiter,用于实现单机的限流,并给出类似的代码:

    public void method() {
        RateLimiter rateLimiter = RateLimiter.create(10);
        if(rateLimiter.tryAcquire()){
            // do business
            ......
        }
    }
    

    可是上面的代码真的能限流吗?

    首先,从代码逻辑角度来讲,方法在每次被调用是都new一个RateLimiter,不同请求之间毫无关联,怎么能起到限流的作用呢?

    其次,经过本人实际验证,上面的方法运行结果表明,根本没有限流的作用。

    正确使用

    在SpringMVC项目中,controller、service等对应的bean都是单例,因此将RateLimiter作为bean的属性并初始化,再加上RateLimiter的注释中表示RateLimiter是并发安全的:

    RateLimiter is safe for concurrent use: It will restrict the total rate of calls from all threads. Note, however, that it does not guarantee fairness.

    因此,正确的写法如下:

    private RateLimiter rateLimiter = RateLimiter.create(10);
    
    public void method() {
        if(rateLimiter.tryAcquire()){
            // do business
            ......
        }
    }
    
  • 相关阅读:
    内存溢出
    接手新业务
    pjb fabu
    中文手册
    人背的时候,做啥都失败
    帮助开发人员学习
    python中的__dict__,__getattr__,__setattr__
    NetCore在Docker中发布及运行
    ELK基础配置
    IdentityServer4 手动验签及日志记录
  • 原文地址:https://www.cnblogs.com/acode/p/9260068.html
Copyright © 2011-2022 走看看