zoukankan      html  css  js  c++  java
  • Guava的RateLimiter实现接口限流

    最近开发需求中有需要对后台接口进行限流处理,整理了一下基本使用方法。

    首先添加guava依赖:

        <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>23.0</version>
        </dependency>

    然后封装RateLimiter适用对多接口的限制:

    import com.google.common.util.concurrent.RateLimiter;
    import org.springframework.util.StringUtils;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.TimeUnit;
    
    public class RateLimiterFactory {
    
        private static ConcurrentHashMap<String, RateLimiter> limiterMap = new ConcurrentHashMap<>();
    
        //每秒许可证数量
        private static double permitsPerSecond = 1000;
    
        //等待超时时间
        private static long timeout = 4L;
    
        /**
         *@param apiId 对应接口的id
         *@description 获取许可
         */
        public static boolean tryAcquire(String apiId) {
            //如果传入apiId为空则返回true
            if (StringUtils.isEmpty(apiId)) {
                return true;
            }
            limiterMap.putIfAbsent(apiId, RateLimiter.create(permitsPerSecond));
            return limiterMap.get(apiId).tryAcquire(timeout, TimeUnit.SECONDS);
        }
    
    }

    使用RateLimiterFactory实现对接口的限制:

    @Controller
    public class TestController {
    
        ...
    
        @RequestMapping("/test")
        @ResponseBody
        public String test(){
            if(!RateLimiterFactory.tryAcquire(ApiInfo.TEST)) {
                return "当前请求数过高!";
            }
            ...
        }
    }

    以上就是RateLimiter实现接口限流的常见使用,头一次发文,mark一下。

  • 相关阅读:
    hdu 2296 AC自动机+DP+路径字符串记录(较麻烦)
    HDU
    hdu 2243(poj2778的加强版!(AC自动机+矩阵))
    Poj3691(AC自动机+DP(简单题))
    后台样式升级1.
    那些可以在数据库里做的事:分页与过滤
    常用的几个单页应用程序网站分享
    Javascript生成二维码(QR)
    户端页面中读取串口操作
    GridView事件分析
  • 原文地址:https://www.cnblogs.com/cord/p/9226667.html
Copyright © 2011-2022 走看看