跟我學SpringCloud | 第十四篇:Spring Cloud Gateway高級應用

SpringCloud系列教程 | 第十四篇:Spring Cloud Gateway高級應用

Springboot: 2.1.6.RELEASEhtml

SpringCloud: Greenwich.SR1react

如無特殊說明,本系列教程全採用以上版本git

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

  • 熔斷
  • 限流
  • 重試

1. 限速路由器

限速在高併發場景中比較經常使用的手段之一,能夠有效的保障服務的總體穩定性,Spring Cloud Gateway 提供了基於 Redis 的限流方案。因此咱們首先須要添加對應的依賴包spring-boot-starter-data-redis-reactiveredis

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

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

server:
  port: 8080
spring:
  application:
    name: spring-cloud-gateway
  redis:
    host: localhost
    password: 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 類。併發

package com.springcloud.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * Created with IntelliJ IDEA.
 *
 * @Date: 2019/7/11
 * @Time: 23:45
 * @email: inwsy@hotmail.com
 * Description:
 */
@Configuration
public class Config {
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }
}

Config類須要加@Configuration註解。app

根據請求參數中的 user 字段來限流,也能夠設置根據請求 IP 地址來限流,設置以下:spring-boot

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

這樣網關就能夠根據不一樣策略來對請求進行限流了。高併發

2. 熔斷路由器

在以前的 Spring Cloud 系列文章中,你們對熔斷應該有了必定的瞭解,如過不了解能夠先讀這篇文章:《跟我學SpringCloud | 第四篇:熔斷器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。

3. 重試路由器

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 個值。

以上即是項目中經常使用的一些網關操做,更多關於 Spring Cloud GateWay 的使用請參考官網。

spring-cloud-gateway官網

示例代碼-Github

參考:

https://cloud.spring.io/spring-cloud-gateway/single/spring-cloud-gateway.html https://windmt.com/2018/05/11/spring-cloud-16-spring-cloud-gateway-others/

相關文章
相關標籤/搜索