Zuul:構建高可用閘道器之多維度限流

冷冷gg發表於2017-12-12
  • 對請求的目標URL進行限流(例如:某個URL每分鐘只允許呼叫多少次)
  • 對客戶端的訪問IP進行限流(例如:某個IP每分鐘只允許請求多少次)
  • 對某些特定使用者或者使用者組進行限流(例如:非VIP使用者限制每分鐘只允許呼叫100次某個API等)
  • 多維度混合的限流。此時,就需要實現一些限流規則的編排機制。與、或、非等關係。

介紹

spring-cloud-zuul-ratelimit是和zuul整合提供分散式限流策略的擴充套件,只需在yaml中配置幾行配置,就可使應用支援限流

<dependency>
    <groupId>com.marcosbarbero.cloud</groupId>
    <artifactId>spring-cloud-zuul-ratelimit</artifactId>
    <version>1.3.4.RELEASE</version>
</dependency>
複製程式碼

支援的限流粒度

  • 服務粒度 (預設配置,當前服務模組的限流控制)

  • 使用者粒度 (詳細說明,見文末總結)

  • ORIGIN粒度 (使用者請求的origin作為粒度控制)

  • 介面粒度 (請求介面的地址作為粒度控制)

  • 以上粒度自由組合,又可以支援多種情況。

  • 如果還不夠,自定義RateLimitKeyGenerator實現。

//預設實現
public String key(final HttpServletRequest request, final Route route, final RateLimitProperties.Policy policy) {
    final List<Type> types = policy.getType();
    final StringJoiner joiner = new StringJoiner(":");
    joiner.add(properties.getKeyPrefix());
    if (route != null) {
        joiner.add(route.getId());
    }
    if (!types.isEmpty()) {
        if (types.contains(Type.URL) && route != null) {
            joiner.add(route.getPath());
        }
        if (types.contains(Type.ORIGIN)) {
            joiner.add(getRemoteAddr(request));
        }
        // 這個結合文末總結。
        if (types.contains(Type.USER)) {
            joiner.add(request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : ANONYMOUS_USER);
        }
    }
    return joiner.toString();
}
複製程式碼

支援的儲存方式

image

  • InMemoryRateLimiter - 使用 ConcurrentHashMap作為資料儲存
  • ConsulRateLimiter - 使用 Consul 作為資料儲存
  • RedisRateLimiter - 使用 Redis 作為資料儲存
  • SpringDataRateLimiter - 使用 資料庫 作為資料儲存

限流配置

  • limit 單位時間內允許訪問的個數
  • quota 單位時間內允許訪問的總時間(統計每次請求的時間綜合)
  • refresh-interval 單位時間設定
zuul:
  ratelimit:
    key-prefix: your-prefix 
    enabled: true 
    repository: REDIS 
    behind-proxy: true
    policies:
      myServiceId:
        limit: 10
        quota: 20
        refresh-interval: 30
        type:
          - user
        
複製程式碼

以上配置意思是:30秒內允許10個訪問,並且要求總請求時間小於20秒

效果展示

yaml配置:

zuul:
  ratelimit:
    key-prefix: pig-ratelimite 
    enabled: true 
    repository: REDIS 
    behind-proxy: true
    policies:
      pig-admin-service:
        limit: 2
        quota: 1
        refresh-interval: 3
複製程式碼

動態圖 ↓↓↓↓↓

image

Redis 中資料結構 注意紅色字型

image

總結

  • 可以使用Spring Boot Actuator 提供的服務狀態,動態設定限流開關
  • 原始碼可以參考:gitee.com/log4j/pig
  • 使用者限流的實現:如果你的專案整合 Shiro 或者 Spring Security 安全框架,那麼會自動維護request域UserPrincipal,如果是自己的框架,請登入成功後維護request域UserPrincipal,才能使用使用者粒度的限流。未登入預設是:anonymous

相關文章