spring cloud gateway系列教程1—Route Predicate

13 篇文章 0 订阅

spring cloud gateway系列教程目录

  1. spring cloud gateway系列教程1—Route Predicate
  2. spring cloud gateway系列教程2——GatewayFilter_上篇
  3. spring cloud gateway系列教程2——GatewayFilter_下篇
  4. spring cloud gateway系列教程3—Global Filters
  5. spring cloud gateway系列教程4—其他配置

怎么引入spring cloud gateway

maven上,只需引入如下依赖即可:

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

引入了依赖默认即开启gateway了,如果暂时不想使用这个功能,这可以配置spring.cloud.gateway.enabled=false即可。

Spring Cloud Gateway使用的是Spring Boot和Spring Webflux提供的Netty底层环境,不能和传统的Servlet容器一起使用,也不能打包成一个WAR包。

工作原理

当客户端发送请求到Spring Cloud Gateway,Gateway Handler Mapping会匹配Route映射分发到Gateway Web Handler。handler会将请求经过一系列的filter处理,代理请求前,会执行左右的"pre" filter逻辑,代理请求后,会执行所有"post" filter逻辑。

Route Predicate Factories

Spring Cloud Gateway是使用Spring WebFlux的HandlerMapping作为匹配路由底层实现,本身已自带很多Route Predicate Factories,分别匹配不同的http请求属性,多个Route Predicate Factories也可以通过and进行逻辑合并匹配。

1. After Route Predicate Factory

After Route Predicate Factory使用的是时间作为匹配规则,只要当前时间大于设定时间,路由才会匹配请求。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: http://www.google.com
        predicates:
        - After=2018-12-25T14:33:47.789+08:00

这个路由规则会在东8区的2018-12-25 14:33:47后,将请求都转跳到google。

2. Before Route Predicate Factory

Before Route Predicate Factory也是使用时间作为匹配规则,只要当前时间小于设定时间,路由才会匹配请求。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: http://www.google.com
        predicates:
        - Before=2018-12-25T14:33:47.789+08:00

这个路由规则会在东8区的2018-12-25 14:33:47前,将请求都转跳到google。

3. Between Route Predicate Factory

Between Route Predicate Factory也是使用两个时间作为匹配规则,只要当前时间大于第一个设定时间,并小于第二个设定时间,路由才会匹配请求。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: http://www.google.com
        predicates:
        - Between=2018-12-25T14:33:47.789+08:00, 2018-12-26T14:33:47.789+08:00

这个路由规则会在东8区的2018-12-25 14:33:47到2018-12-26 14:33:47之间,将请求都转跳到google。

4. Cookie Route Predicate Factory

Cookie Route Predicate Factory使用的是cookie名字和正则表达式的value作为两个输入参数,请求的cookie需要匹配cookie名和符合其中value的正则。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: http://www.google.com
        predicates:
        - Cookie=cookiename, cookievalue

路由匹配请求存在cookie名为cookiename,cookie内容匹配cookievalue的,将请求转发到google。

5. Header Route Predicate Factory

Header Route Predicate Factory,与Cookie Route Predicate Factory类似,也是两个参数,一个header的name,一个是正则匹配的value。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: http://www.google.com
        predicates:
        - Header=X-Request-Id, \d+

路由匹配存在名为X-Request-Id,内容为数字的header的请求,将请求转发到google。

6. Host Route Predicate Factory

Host Route Predicate Factory使用的是host的列表作为参数,host使用Ant style匹配。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://www.google.com
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

路由会匹配Host诸如:www.somehost.orgbeta.somehost.orgwww.anotherhost.org等请求。

7. Method Route Predicate Factory

Method Route Predicate Factory是通过HTTP的method来匹配路由。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: http://www.google.com
        predicates:
        - Method=GET

路由会匹配到所有GET方法的请求。

8. Path Route Predicate Factory

Path Route Predicate Factory使用的是path列表作为参数,使用Spring的PathMatcher匹配path,可以设置可选变量。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://www.google.com
        predicates:
        - Path=/foo/{segment},/bar/{segment}

上面路由可以匹配诸如:/foo/1/foo/bar/bar/baz
其中的segment变量可以通过下面方式获取:

PathMatchInfo variables = exchange.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE);
Map<String, String> uriVariables = variables.getUriVariables();
String segment = uriVariables.get("segment");

在后续的GatewayFilter Factories就可以做对应的操作了。

9. Query Route Predicate Factory

Query Route Predicate Factory可以通过一个或两个参数来匹配路由,一个是查询的name,一个是查询的正则value。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://www.google.com
        predicates:
        - Query=baz

路由会匹配所有包含baz查询参数的请求。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://www.google.com
        predicates:
        - Query=foo, ba.

路由会匹配所有包含baz,并且baz的内容为诸如:barbaz等符合ba.正则规则的请求。

10. RemoteAddr Route Predicate Factory

RemoteAddr Route Predicate Factory通过无类别域间路由(IPv4 or IPv6)列表匹配路由。
application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: http://www.google.com
        predicates:
        - RemoteAddr=192.168.1.1/24

上面路由就会匹配RemoteAddr诸如192.168.1.10等请求。

10.1 Modifying the way remote addresses are resolved

RemoteAddr Route Predicate Factory默认情况下,使用的是请求的remote address。但是如果Spring Cloud Gateway是部署在其他的代理后面的,如Nginx,则Spring Cloud Gateway获取请求的remote address是其他代理的ip,而不是真实客户端的ip。

考虑到这种情况,你可以自定义获取remote address的处理器RemoteAddressResolver。当然Spring Cloud Gateway也提供了基于X-Forwarded-For请求头的XForwardedRemoteAddressResolver
熟悉Http代理协议的,都知道X-Forwarded-For头信息做什么的,不熟悉的可以自己谷歌了解一下。

XForwardedRemoteAddressResolver提供了两个静态方法获取它的实例:
XForwardedRemoteAddressResolver::trustAll得到的RemoteAddressResolver总是获取X-Forwarded-For的第一个ip地址作为remote address,这种方式就比较容易被伪装的请求欺骗,模拟请求很容易通过设置初始的X-Forwarded-For头信息,就可以欺骗到gateway。

XForwardedRemoteAddressResolver::maxTrustedIndex得到的RemoteAddressResolver则会在X-Forwarded-For信息里面,从右到左选择信任最多maxTrustedIndex个ip,因为X-Forwarded-For是越往右是越接近gateway的代理机器ip,所以是越往右的ip,信任度是越高的。
那么如果前面只是挡了一层Nginx的话,如果只需要Nginx前面客户端的ip,则maxTrustedIndex取1,就可以比较安全地获取真实客户端ip。

使用java的配置:
GatewayConfig.java

RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("http://www.google.com")
.route("proxied-route",
    r -> r.remoteAddr(resolver,  "10.10.1.1", "10.10.1.1/24")
        .uri("http://www.google.com")
)

这一章节讲的了几种Route Predicate Factory的使用及场景,下一章节讲GatewayFilter Factories的使用

如果想查看其他spring cloud gateway的案例和使用,可以点击查看

微信扫码订阅
UP更新不错过~
关注
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
一、Spring Cloud Hystrix 1. 什么是 Hystrix Hystrix 是一个延迟和容错库,用于隔离依赖服务的访问点,以防止这些依赖服务的故障导致雪崩效应。它提供了熔断、限流和降级等机制,保障了对依赖服务的访问。 2. Hystrix的核心概念 熔断:在一段时间内,如果服务的错误比例超过了设定的阈值,那么这个服务就会被熔断,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { int i = new Random().nextInt(10); if (i % 2 == 0) { throw new RuntimeException("error"); } return "success"; } public String fallbackMethod(){ return "fallback"; } ``` 限流:在一段时间内,如果服务的请求数量超过了设定的阈值,那么这个服务就会被限流,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"), @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000")}) public String method() { return "success"; } public String fallbackMethod(){ return "fallback"; } ``` 降级:在一段时间内,如果依赖服务不可用,那么就会调用预先备选的服务逻辑或返回预先设定的响应,示例代码: ``` @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { return restTemplate.getForObject("http://service-provider/method", String.class); } public String fallbackMethod(){ return "fallback"; } ``` 3. Hystrix的集成 添加依赖 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> ``` 开启熔断 ``` @SpringBootApplication @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 添加注解 ``` @Service public class Service { @HystrixCommand(fallbackMethod = "fallbackMethod") public String method() { return "success"; } public String fallbackMethod() { return "fallback"; } } ``` 4. 测试 启动服务后,访问 http://localhost:8080/method,可以看到服务正常返回"success"。将calledOnce设置为false并再次访问该URL,可以看到服务返回"fallback"。 二、Spring Cloud Gateway 1. 什么是 Gateway GatewaySpring Cloud 提供的一种 API 网关服务,基于 Spring 5.0、Spring Boot 2.0 和 Project Reactor 等技术开发。 2. Gateway 的三种机制 熔断:默认使用 Hystrix 进行熔断,示例代码: ``` spring.cloud.gateway.routes.id=route1 spring.cloud.gateway.routes.uri=http://httpbin.org:80 spring.cloud.gateway.routes.predicate[0]=Host=**.somehost.org spring.cloud.gateway.routes.predicate[1]=Path=/get spring.cloud.gateway.routes.filters[0]=Hystrix=hystrixCommandName ``` 限流:使用 RequestRateLimiter Gateway Filter 进行限流,示例代码: ``` spring.cloud.gateway.routes[0].id=count_route spring.cloud.gateway.routes[0].uri=http://httpbin.org:80 spring.cloud.gateway.routes[0].predicates[0]=Path=/get spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=my-limiter-key,2,10,PT1S ``` 降级:可以使用 Hystrix 进行降级,示例代码: ``` spring.cloud.gateway.routes[0].id=test_route spring.cloud.gateway.routes[0].uri=http://localhost:9090 spring.cloud.gateway.routes[0].predicates[0]=Path=/test spring.cloud.gateway.routes[0].filters[0]=Hystrix=mycommand ``` 3. Gateway 的集成 添加依赖 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ``` 4. 测试 启动服务后,访问 http://localhost:8080/get,可以看到服务正常返回。将请求频率配置为 0.1s,再次访问该 URL,可以看到服务返回 429 Too Many Requests。 参考资料: 1. Spring Cloud Hystrix 官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.2.1.RELEASE/reference/html/#spring-cloud-hystrix 2. Spring Cloud Gateway 官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二当家的黑板报

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值