springboot: 2.1.6.release
springcloud: greenwich.sr1
如无特殊说明,本系列教程全采用以上版本
上一篇我们聊了gateway和注册中心的使用,以及 gataway 中 filter 的基本使用,这篇文章我们将继续介绍 filter 的一些高级功能。
限速在高并发场景中比较常用的手段之一,可以有效的保障服务的整体稳定性,spring cloud gateway 提供了基于 redis 的限流方案。所以我们首先需要添加对应的依赖包spring-boot-starter-data-redis-reactive
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis-reactive</artifactid> </dependency>
配置文件中需要添加 redis 地址和限流的相关配置
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
项目中设置限流的策略,创建 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注解。
根据请求参数中的 user 字段来限流,也可以设置根据请求 ip 地址来限流,设置如下:
@bean public keyresolver ipkeyresolver() { return exchange -> mono.just(exchange.getrequest().getremoteaddress().gethostname()); }
这样网关就可以根据不同策略来对请求进行限流了。
在之前的 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。
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。
以上便是项目中常用的一些网关操作,更多关于 spring cloud gateway 的使用请参考官网。
如对本文有疑问, 点击进行留言回复!!
Spring Cloud Alibaba系列,nacos作为服务配置中心
Spring Cloud Alibaba系列(一)nacos作为服务注册中心
网友评论