限速在高併發場景中比較經常使用的手段之一,能夠有效的保障服務的總體穩定性,Spring Cloud Gateway 提供了基於 Redis 的限流方案。因此咱們首先須要添加對應的依賴包spring-boot-starter-data-redis-reactivejava
`<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>`COPY
配置文件中須要添加 Redis 地址和限流的相關配置react
`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`COPY
項目中設置限流的策略,建立 Config 類。redis
`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")); } }` COPY
Config類須要加@Configuration註解。spring
根據請求參數中的 user 字段來限流,也能夠設置根據請求 IP 地址來限流,設置以下:segmentfault
`@Bean public KeyResolver ipKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName()); }`COPY
這樣網關就能夠根據不一樣策略來對請求進行限流了。架構
在以前的 Spring Cloud 系列文章中,你們對熔斷應該有了必定的瞭解,如過不了解能夠先讀這篇文章:《跟我學SpringCloud | 第四篇:熔斷器Hystrix》併發
Spring Cloud Gateway 也能夠利用 Hystrix 的熔斷特性,在流量過大時進行服務降級,一樣咱們仍是首先給項目添加上依賴。app
`<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>`COPY
配置示例spring-boot
`spring: cloud: gateway: routes: - id: hystrix_route uri: http://example.org filters: - Hystrix=myCommandName`COPY
配置後,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`COPY
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`COPY
Retry GatewayFilter 經過這四個參數來控制重試機制: retries, statuses, methods, 和 series。