Spring Cloud Gateway 限流詳解

 

Spring Cloud Gatway內置的 RequestRateLimiterGatewayFilterFactory 提供限流的能力,基於令牌桶算法實現。目前,它內置的 RedisRateLimiter ,依賴Redis存儲限流配置,以及統計數據。固然你也能夠實現本身的RateLimiter,只需實現 org.springframework.cloud.gateway.filter.ratelimit.RateLimiter 接口,或者繼承 org.springframework.cloud.gateway.filter.ratelimit.AbstractRateLimiter 。php

漏桶算法react

想象有一個水桶,水桶以必定的速度出水(以必定速率消費請求),當水流速度過大水會溢出(訪問速率超過響應速率,就直接拒絕)。redis

漏桶算法的兩個變量:算法

水桶漏洞的大小:rate最多能夠存多少的水:burstspring

令牌桶算法ide

系統按照恆定間隔向水桶裏加入令牌(Token),若是桶滿了的話,就不加了。每一個請求來的時候,會拿走1個令牌,若是沒有令牌可拿,那麼就拒絕服務。spring-boot

TIPS測試

Redis Rate Limiter的實現基於這篇文章: Stripe[1]Spring官方引用的令牌桶算法文章: Token Bucket Algorithm[2] ,有興趣能夠看看。spa

寫代碼

1 加依賴:code

  •  
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis-reactive</artifactId></dependency>


2 寫配置:

  •  
spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: lb://user-center
          predicates:
            - TimeBetween=上午0:00,下午11:59
          filters:
            - AddRequestHeader=X-Request-Foo, Bar
            - name: RequestRateLimiter
              args:
                # 令牌桶每秒填充平均速率
                redis-rate-limiter.replenishRate: 1
                # 令牌桶的上限
                redis-rate-limiter.burstCapacity: 2
                # 使用SpEL表達式從Spring容器中獲取Bean對象
                key-resolver: "#{@pathKeyResolver}"
  redis:
    host: 127.0.0.1
    port: 6379


3 寫代碼:按照X限流,就寫一個針對X的KeyResolver。

  •  
@Configuration
public class Raonfiguration {
    /**
     * 按照Path限流
     *
     * @return key
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(
            exchange.getRequest()
                .getPath()
                .toString()
        );
    }
}


4 這樣,限流規則便可做用在路徑上。

  •  
例如:# 訪問:http://${GATEWAY_URL}/users/1,對於這個路徑,它的redis-rate-limiter.replenishRate = 1,redis-rate-limiter.burstCapacity = 2;# 訪問:http://${GATEWAY_URL}/shares/1,對這個路徑,它的redis-rate-limiter.replenishRate = 1,redis-rate-limiter.burstCapacity = 2;


測試

持續高速訪問某個路徑,速度過快時,返回 HTTP ERROR 429 。

拓展

你也能夠實現針對用戶的限流:

  • @Beanpublic KeyResolver userKeyResolver() {    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));}

針對來源IP的限流:

  •  
@Bean
public KeyResolver ipKeyResolver() {
  return exchange -> Mono.just(
    exchange.getRequest()
    .getHeaders()
    .getFirst("X-Forwarded-For")
  );
}

 

References

[1] Stripe: https://stripe.com/blog/rate-limiters
[2] Token Bucket Algorithm: https://en.wikipedia.org/wiki/Token_bucket


watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=

相關文章
相關標籤/搜索