springcloud(十三):服務網關 Spring Cloud GateWay 熔斷、限流、重試

上篇文章介紹了 Gataway 和註冊中心的使用,以及 Gataway 中 Filter 的基本使用,這篇文章我們將繼續介紹 Filter 的一些常用功能。

修改請求路徑的過濾器

StripPrefix Filter

StripPrefix Filter 是一個請求路徑截取的功能,我們可以利用這個功能來做特殊業務的轉發。

application.yml 配置如下:

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: http://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2

上面這個配置的例子表示,當請求路徑匹配到/name/**會將包含name和後邊的字符串接去掉轉發, StripPrefix=2就代表截取路徑的個數,這樣配置後當請求/name/bar/foo後端匹配到的請求路徑就會變成http://nameservice/foo

我們還是在 cloud-gateway-eureka 項目中進行測試,修改 application.yml 如下:

spring:
  cloud:
     routes:
     - id: nameRoot
       uri: lb://spring-cloud-producer
       predicates:
       - Path=/name/**
       filters:
       - StripPrefix=2

配置完後重啓 cloud-gateway-eureka 項目,訪問地址:http://localhost:8888/name/foo/hello頁面會交替顯示:

hello world!
hello world smile!

和直接訪問地址 http://localhost:8888/hello展示的效果一致,說明請求路徑中的 name/foo/ 已經被截取。

PrefixPath Filter

PrefixPath Filter 的作用和 StripPrefix 正相反,是在 URL 路徑前面添加一部分的前綴

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: http://example.org
        filters:
        - PrefixPath=/mypath

大家可以下來去測試,這裏不在演示。

限速路由器

限速在高併發場景中比較常用的手段之一,可以有效的保障服務的整體穩定性,Spring Cloud Gateway 提供了基於 Redis 的限流方案。所以我們首先需要添加對應的依賴包spring-boot-starter-data-redis-reactive

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

配置文件中需要添加 Redis 地址和限流的相關配置

spring:
  application:
    name: cloud-gateway-eureka
  redis:
    host: localhost
    password:
    port: 6379
  cloud:
    gateway:
     discovery:
        locator:
         enabled: true
     routes:
     - id: requestratelimiter_route
       uri: http://example.org
       filters:
       - name: RequestRateLimiter
         args:
           redis-rate-limiter.replenishRate: 10
           redis-rate-limiter.burstCapacity: 20
           key-resolver: "#{@userKeyResolver}"
       predicates:
         - Method=GET
  • filter 名稱必須是 RequestRateLimiter
  • redis-rate-limiter.replenishRate:允許用戶每秒處理多少個請求
  • redis-rate-limiter.burstCapacity:令牌桶的容量,允許在一秒鐘內完成的最大請求數
  • key-resolver:使用 SpEL 按名稱引用 bean

項目中設置限流的策略,創建 Config 類。

public class Config {

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

根據請求參數中的 user 字段來限流,也可以設置根據請求 IP 地址來限流,設置如下:

@Bean
public KeyResolver ipKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}

這樣網關就可以根據不同策略來對請求進行限流了。

熔斷路由器

在之前的 Spring Cloud 系列文章中,大家對熔斷應該有了一定的瞭解,如過不了解可以先讀這篇文章:熔斷器 Hystrix

Spring Cloud Gateway 也可以利用 Hystrix 的熔斷特性,在流量過大時進行服務降級,同樣我們還是首先給項目添加上依賴。

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

配置示例

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: http://example.org
        filters:
        - Hystrix=myCommandName

配置後,gateway 將使用 myCommandName 作爲名稱生成 HystrixCommand 對象來進行熔斷管理。如果想添加熔斷後的回調內容,需要在添加一些配置。

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://spring-cloud-producer
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis

fallbackUri: forward:/incaseoffailureusethis配置了 fallback 時要會調的路徑,當調用 Hystrix 的 fallback 被調用時,請求將轉發到/incaseoffailureuset這個 URI。

重試路由器

RetryGatewayFilter 是 Spring Cloud Gateway 對請求重試提供的一個 GatewayFilter Factory

配置示例:

spring:
  cloud:
    gateway:
      routes:
      - id: retry_test
        uri: lb://spring-cloud-producer
        predicates:
        - Path=/retry
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: BAD_GATEWAY

Retry GatewayFilter 通過這四個參數來控制重試機制: retries, statuses, methods, 和 series。

  • retries:重試次數,默認值是 3 次
  • statuses:HTTP 的狀態返回碼,取值請參考:org.springframework.http.HttpStatus
  • methods:指定哪些方法的請求需要進行重試邏輯,默認值是 GET 方法,取值參考:org.springframework.http.HttpMethod
  • series:一些列的狀態碼配置,取值參考:org.springframework.http.HttpStatus.Series。符合的某段狀態碼纔會進行重試邏輯,默認值是 SERVER_ERROR,值是 5,也就是 5XX(5 開頭的狀態碼),共有5 個值。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章