spring cloud gateway Zuul RateLimit limiting configuration

Reprinted from: https://www.jianshu.com/p/2fc92a929e8e

Narrative

In order to prevent some API access token is not infinitely large number of calls in the usual projects, the need for some services API limiting. Some like to take some of the interfaces registered or send a verification code, if malicious unlimited calls, how much will cause some of the costs of produce, send text messages or e-mail are some of the more third-party interfaces, number, of course, the more the cost , serious direct crash the service. spring cloud api-gateway introduced limiting arrangement is still necessary.

solution

Zuul RateLimit is introduced in dependence file pom


<dependency>
    <groupId>com.marcosbarbero.cloud</groupId>
    <artifactId>spring-cloud-zuul-ratelimit</artifactId>
    <version>1.3.2.RELEASE</version>
</dependency>

YML 配置


更详细的配置解读下面有写,这里只是简单配置一下,以下这个配置就可以对服务进行限流了
zuul:
  routes: 你的路由配置
    test:
      path: 
      serviceId: 
  ratelimit:
    enabled: true
    policies:
      test: 路由名
        limit: 限制次数
        refresh-interval: 刷新时间
        type: 类型

Column shows

Local yourself a service is configured to the service within a minute API can access only ten times, more than ten times, the gateway will error

zuul:
  routes:
    test:
      path: /api/test/**
      serviceId: hscf-cloud-test-9457
  ratelimit:
    enabled: true
    policies:
      test:
        limit: 10
        refresh-interval: 60
        type: origin  限流方式

The following briefly examine the source code by

RateLimit class inherits ZuulFilter, within the variable is not difficult to see the value of our property in yml configuration file. Part of the source code within RateLimit, filterType as "pre" represents the intercept before each API access, LIMIT_HEADER, REMAINING_HEADER, RESET_HEADER these three variables that should get us to configure the number of visits, as well as the number of visits within the remaining time record .

public class RateLimitFilter extends ZuulFilter {
    public static final String LIMIT_HEADER = "X-RateLimit-Limit";
    public static final String REMAINING_HEADER = "X-RateLimit-Remaining";
    public static final String RESET_HEADER = "X-RateLimit-Reset";

    public String filterType() {
        return "pre";
    }
    public int filterOrder() {
        return -1;
    }
    public boolean shouldFilter() {
        return this.properties.isEnabled() && this.policy(this.route()).isPresent();
    }

Judgment () in the body logic run. First through this.policy (route) .ifPresent ((policy ) policy determines the configuration information exists, it will read the presence
get to the current limit value, there remains a limit value, determining the remaining final limit value is smaller than 0, less than 0 It would have reported abnormal too many requests
TOO_MANY_REQUESTS (429, "too many requests ")

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();
        Route route = this.route();
        this.policy(route).ifPresent((policy) -> {
            String key = this.rateLimitKeyGenerator.key(request, route, policy);
            Rate rate = this.rateLimiter.consume(policy, key);
            response.setHeader("X-RateLimit-Limit", policy.getLimit().toString());
            response.setHeader("X-RateLimit-Remaining", String.valueOf(Math.max(rate.getRemaining().longValue(), 0L)));
            response.setHeader("X-RateLimit-Reset", rate.getReset().toString());
            if(rate.getRemaining().longValue() < 0L) {
                ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
                ctx.put("rateLimitExceeded", "true");
                throw new ZuulRuntimeException(new ZuulException(HttpStatus.TOO_MANY_REQUESTS.toString(), HttpStatus.TOO_MANY_REQUESTS.value(), (String)null));
            }
        });
        return null;
    }
。。。。。。

Exception information console, abnormal code is 429, which is abnormal too many requests: TOO_MANY_REQUESTS (429, "Too Many Requests")

RateLimit detailed configuration information interpretation

zuul:

    ratelimit:

        key-prefix: your-prefix  #对应用来标识请求的key的前缀

        enabled: true

        repository: REDIS  #对应存储类型(用来存储统计信息)

        behind-proxy: true  #代理之后

        default-policy: #可选 - 针对所有的路由配置的策略,除非特别配置了policies

             limit: 10 #可选 - 每个刷新时间窗口对应的请求数量限制

             quota: 1000 #可选-  每个刷新时间窗口对应的请求时间限制(秒)

              refresh-interval: 60 # 刷新时间窗口的时间,默认值 (秒)

               type: #可选 限流方式

                    - user

                    - origin

                    - url

          policies:

                myServiceId: #特定的路由

                      limit: 10 #可选- 每个刷新时间窗口对应的请求数量限制

                      quota: 1000 #可选-  每个刷新时间窗口对应的请求时间限制(秒)

                      refresh-interval: 60 # 刷新时间窗口的时间,默认值 (秒)

                      type: #可选 限流方式

                          - user

                          - origin

                          - url
  • url type flow restrictor is distinguished by the request path
  • origin is distinguished by a client IP address
  • user login is distinguished by user name, including anonymous users
Published 22 original articles · won praise 30 · views 80000 +

Guess you like

Origin blog.csdn.net/lizhengyu891231/article/details/103937805