Spring Cloud Gateway-路由谓词工厂详解(Route Predicate Factories)
TIPS
本文基于Spring Cloud Greenwich SR2编写,兼容Spring Cloud Finchley及更高版本。
这一节来详细探讨Spring Cloud Gateway的路由谓词工厂
(Route Predicate Factories),路由谓词工厂的作用是:符合Predicate的条件,就使用该路由的配置,否则就不管。 只要掌握这一句,掌握路由谓词工厂就比较轻松了。
TIPS
Predicate是Java 8提供的一个函数式编程接口。
本文探讨了Spring Cloud Gateway中内置的谓词工厂,包括:
谓词工厂 |
---|
After |
Before |
Between |
Cookie |
Header |
Host |
Method |
Path |
Query |
RemoteAddr |
路由配置的两种形式
先来探讨Spring Cloud Gateway路由配置的两种姿势:
路由到指定URL
示例1:通配
1 | spring: |
表示访问 GATEWAY_URL/**
会转发到 http://www.itmuch.com/**
TIPS
这段配置不能直接使用,需要和下面的Predicate配合使用才行。
示例2:精确匹配
1 | spring: |
表示访问 GATEWAY_URL/spring-cloud/spring-cloud-stream-pan-ta/
会转发到 http://www.itmuch.com/spring-cloud/spring-cloud-stream-pan-ta/
TIPS
这段配置不能直接使用,需要和下面的Predicate配合使用才行。
路由到服务发现组件上的微服务
示例1:通配
1 | spring: |
表示访问 GATEWAY_URL/**
会转发到 user-center
微服务的 /**
TIPS
这段配置不能直接使用,需要和下面的Predicate配合使用才行。
示例2:精确匹配
1 | spring: |
表示访问 GATEWAY_URL/shares/1
会转发到 user-center
微服务的 /shares/1
TIPS
这段配置不能直接使用,需要和下面的Predicate配合使用才行。
谓词工厂详解
下面正式探讨路由谓词工厂。Spring Cloud Gateway提供了十来种路由谓词工厂。为网关实现灵活的转发提供了基石。
After
示例:
1 | spring: |
TIPS
- 技巧:时间可使用
System.out.println(ZonedDateTime.now());
打印,然后即可看到时区。例如:2019-08-10T16:50:42.579+08:00[Asia/Shanghai]
- 时间格式的相关逻辑:
- 默认时间格式:org.springframework.format.support.DefaultFormattingConversionService#addDefaultFormatters
- 时间格式注册:org.springframework.format.datetime.standard.DateTimeFormatterRegistrar#registerFormatters
Before
示例:
1 | spring: |
Between
示例:
1 | spring: |
Cookie
示例:
1 | spring: |
Header
1 | spring: |
Host
1 | spring: |
Method
1 | spring: |
Path
1 | spring: |
TIPS
建议大家看下这一部分的官方文档,里面有个segment编程技巧。比较简单,留个印象。
https://cloud.spring.io/spring-cloud-static/Greenwich.SR2/single/spring-cloud.html#_path_route_predicate_factory
Query
示例1:
1 | spring: |
示例2:
1 | spring: |
RemoteAddr
示例:
1 | spring: |
TIPS
建议大家看下这一部分的官方文档,有个小编程技巧。比较简单,留个印象。
https://cloud.spring.io/spring-cloud-static/Greenwich.SR2/single/spring-cloud.html#_remoteaddr_route_predicate_factory
评论系统未开启,无法评论!