Spring Cloud Gateway Route Predicate Factory 的使用
Spring Cloud Gateway的使用
一、需求
记录Spring Cloud Gateway的一些用法,不对其原理进行过多的探究。
二、基本组成
1、简介
Spring Cloud Gateway 是 基于Spring boot 5、Spring Boot 2.0和Project Reactor 等技术开发的网关。它旨在为微服务提供一个简单有效的方式来管理api路由。
Spring Cloud Gateway 是基于 Netty 运行的,不能运行在传统的Servlet容器中作为War包运行。
2、核型概念
1、Route 路由
Route是网关的基本组成单元,它是有一个ID,一个目标URI和一组predicates和一组filters组成,如果一组断言结果为真,则匹配路由,目标URI会被访问。
注意:
1、多个 Predicate 之间是 逻辑and 的关系。
2、多个Predicate是从定义的顺序从上到下依次执行,也可以指定 order 属性的值。
2、Predicate 谓语、断言
Predicate 是Java 8 Function interface。输入类型是Spring Framework ServerWebExchange。可以用来匹配HTTP请求中的任何内容,例如headers 或者 parameters。
3、Filter 过滤器
Filter是GatewayFilter的实例。通过Filter我们可以在请求发送或返回下游服务时 修改 请求和响应。
3、工作原理
三、网关 Predicate配置方式
1、快捷配置方式(配置文件)
快捷方式是由过滤器是的名称识别,后面紧跟=,在跟以逗号(,)分隔的参数值。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- Cookie=mycookie,mycookievalue
上一个示例使用两个参数定义了Cookie Route Predicate Factory,这两个参数是cookie名称,mycookie和与mycookievalue匹配的值
2、完全展开的参数(配置文件)
name:指定谓词工厂的名字
args:指定对应谓词工厂中的参数对应的值。
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- name: Cookie
args:
name: mycookie
regexp: mycookievalue
这种方式配置和上面的快捷方式配置的是一个意思
3、上方2种方式配置和代码对应关系

4、uri 值的方式
1、以http开头
当匹配到这个路由后,会跳转到这个地址。
2、以 lb 开头
eg:
uri: lb://service-name
解释:
lb:表示负载均衡的意思
service-name:值的是调用服务在注册中心注册的服务名。
四、Route Predicate Factories
Spring Cloud Gateway内置了特别多的路由谓词工厂,用来匹配http请求。当多个一起使用时,是and的关系,即需要所有的谓词工厂都匹配,才匹配这个路由。
1、After
1、描述:
当前请求在指定时间之后才匹配
2、存在参数:
datetime 数据类型是 ZonedDateTime,带有时区
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- After=2020-11-01T11:05:08.020+08:00[Asia/Shanghai]
2、Before
1、描述:
当前请求在指定时间之前才匹配
2、存在参数:
datetime 数据类型是 ZonedDateTime,带有时区
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Before=2020-11-01T11:05:08.020+08:00[Asia/Shanghai]
3、Between
1、描述:
当前请求在指定时间中间才匹配
2、存在参数:
datetime1 数据类型是 ZonedDateTime,带有时区
datetime2 数据类型是 ZonedDateTime,带有时区
并且 datetime1 必须< datetime2
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Between=2020-11-01T11:08:08.020+08:00[Asia/Shanghai],2020-11-01T11:15:08.020+08:00[Asia/Shanghai]
4、Cookie
1、描述:
当前请求中的cookie值匹配配置的cookie参数值时生效
2、存在参数:
name 请求cookie中的参数的名字
regexp 请求cookie中的参数的值,配置的值是Java中的正则表达式形式。
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Cookie=token,tokenvalue\d+

4、解释
- Cookie=token,tokenvalue\d+
表示 请求中必须存在一个 cookie 的key 是 token 的,且值必须是tokenvalue 后面加上一个数子才匹配的上,否则匹配不上。
5、Header
1、描述:
当前请求中的header值匹配配置的header参数值时生效
2、存在参数:
name header key的名字
regexp header key对应的值,配置的值是Java中的正则表达式形式。
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Header=X-Token-Id,\d+
4、解释
- Header=X-Token-Id,\d+
表示请求头中必须存在R-Token-Id且它的值必须是数字
6、Host
1、描述:
匹配请求头中的Host的值
2、存在参数:
patterns 配置一系列的以.作为分隔的ant风格host地址,多个中间以,隔开。Host中配置的值还支持URI template variables,比如{xxx}.baidu.com
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Host=**.gateway.com,{study}.baidu.com

4、解释
- Host=**.gateway.com,{study}.baidu.com
1、**.gateway.com:表示请求中的Host的值需要配置这种ant风格
2、{study}.baidu.com:study这个模版变量可以在GatewayFilter中获取到,通过ServerWebExchange.getAttributes().get(ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE)获取
7、Method
1、描述:
匹配请求头中的Method的值
2、存在参数:
methods 需要匹配的方法,比如GET、POST等
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Method=GET,POST,PUT # 只有get,post,put请求才能匹配上方这个路由
8、Path
1、描述:
匹配请求路径。
2、存在参数:
patterns 需要匹配的路径eg: /product/{id},/product/**
matchOptionalTrailingSeparator 一个可选的参数
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- Path=/product/findOne/{productId},/product/**
4、解释
/product/findOne/{productId} 支持uri模版变量,productId可以在GatewayFilter中获取,获取方式.
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);
String segment = uriVariables.get("productId");
9、Query
1、描述:
匹配请求参数。
2、存在参数:
param 请求参数的key值
regexp 请求参数的值,配置的值是Java中的正则表达式形式。
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
#- Query=pwd
- Query=username,\d+
4、解释
1、Query=pwd 表示请求中必须存在 pwd这个请求参数
2、Query=username,\d+ 表示请求中必须存在username这个参数,且它的值必须是数字
10、RemoteAddr
1、描述:
匹配请求的ip地址,支持ipv4和ipv6。
2、存在参数:
sources 地址列表eg:127.0.0.1/16 后方的/16是子网掩码
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider # 名字唯一即可
uri: lb://product-provider
predicates:
- RemoteAddr=127.0.0.1/16
4、注意
如果我们的Spring Cloud Gateway是位于代理后面,那么获取到远程地址可能不正确,此时我们可以自己编写一个RemoteAddressResolver来解决。
11、Weight
1、描述:
根据权重来分发请求,权重是根据group来计算的。
2、存在参数:
group 组,权重根据组来计算
weight 权重值,是一个 Int 的值
3、配置实例
spring:
cloud:
gateway:
routes:
- id: product-provider
uri: https://weighthigh.org
predicates:
- Weight=group1,8
- id: user-consumer
uri: https://weightlow.org
predicates:
- Weight=group1,2
4、解释
上方配置会导致80%的请求落到 https://weighthigh.org,有20%的请求落到https://weightlow.org
五、自己编写一个 route predicate factory
1、编写步骤
1、编写一个类,实现RoutePredicateFactory接口,或继承AbstractRoutePredicateFactory
> 1、AbstractRoutePredicateFactory 中的 C 表示 配置文件类
> 2、重写shortcutFieldOrder此方法,表示的配置文件中参数的位置
> 3、重写apply(C c)方法,表示的是具体的业务逻辑
2、我们自己编写的类必须要以RoutePredicateFactory结尾,否则比较麻烦,参考
org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator#initFactories 这个方法。
2、要实现的功能
判断请求参数中是否存在 token 配置的值。
3、Java代码
@Slf4j
@Component
public class TokenRoutePredicateFactory extends AbstractRoutePredicateFactory<TokenRoutePredicateFactory.Config> {
public TokenRoutePredicateFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Lists.newArrayList("token");
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return exchange -> {
log.info("判断请求头中是否存在token这个参数");
String token = exchange.getRequest().getQueryParams().getFirst(config.getToken());
return StringUtils.isNotBlank(token);
};
}
@Data
public static class Config {
private String token;
}
}
4、配置文件
spring:
cloud:
gateway:
routes:
- id: product-provider
uri: lb://product-provider
predicates:
- Token=token
5、解释

六、完整代码
https://gitee.com/huan1993/spring-cloud-alibaba-parent/tree/master/gateway
七、参考链接
https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/
Spring Cloud Gateway Route Predicate Factory 的使用的更多相关文章
- Spring Cloud Gateway 之 AddRequestHeader GatewayFilter Factory
今天我们来学习下GatewayFilter Factory,中文解释就是过滤器工厂. 官方文档对GatewayFilter Factory的介绍: Route filters allow the mo ...
- spring cloud gateway 深入了解 - Predicate
文章来源 spring cloud gateway 通过谓词(Predicate)来匹配来自用户的请求 为了方便,使用postman测试不同的谓词的效果 路径谓词(Predicate)—— 最简单的谓 ...
- Spring Cloud Gateway实战之四:内置predicate小结
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- spring cloud gateway之filter篇
转载请标明出处: https://www.fangzhipeng.com 本文出自方志朋的博客 在上一篇文章详细的介绍了Gateway的Predict,Predict决定了请求由哪一个路由处理,在路由 ...
- 微服务网关 Spring Cloud Gateway
1. 为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...
- 网关我选 Spring Cloud Gateway
网关可提供请求路由与组合.协议转换.安全认证.服务鉴权.流量控制与日志监控等服务.可选的网关有不少,比如 Nginx.高性能网关 OpenResty.Linkerd 以及 Spring Cloud G ...
- Spring Cloud gateway 网关服务二 断言、过滤器
微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...
- Spring Cloud gateway 网关四 动态路由
微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...
- Spring Cloud Gateway - 路由法则
1. After Route Predicate Factory 输入一个参数:时间,匹配该时间之后的请求,示例配置: spring: cloud: gateway: routes: - id: af ...
随机推荐
- FlinkCDC 2.0使用实践体验
一.背景说明 所谓CDC:全称是 Change Data Capture ,在广义的概念上,只要能捕获数据变更的技术,我们都可以称为 CDC .通常我们说的 CDC 技术主要面向数据库的变更,是一种用 ...
- 取消input默认提示框
input输入框有自动保存记忆功能,点击的时候之前输入的内容会在下拉框自动提示 autocomplete="off",这是H5的一个属性. <input type=" ...
- Activiti 学习(四)—— Activiti 结合实际业务
流程实例 流程实例(ProcessInstance)代表流程定义的执行实例.一个流程实例包括了所有的运行节点.我们可以利用这个对象来了解当前流程实例的进度等信息.例如:用户或程序按照流程定义内容发起一 ...
- 机器学习——正则化方法Dropout
1 前言 2012年,Dropout的想法被首次提出,受人类繁衍后代时男女各一半基因进行组合产生下一代的启发,论文<Dropout: A Simple Way to Prevent Neural ...
- 最小生成树-普利姆(Prim)算法
最小生成树-普利姆(Prim)算法 最小生成树 概念:将给出的所有点连接起来(即从一个点可到任意一个点),且连接路径之和最小的图叫最小生成树.最小生成树属于一种树形结构(树形结构是一种特殊的图),或者 ...
- CentOS8部署nextcloud网盘
Nextcloud是一款开源的存储软件,功能丰富,支持多人协同工作,目前完全免费. 官网:https://www.nextcloud.com 架构:LAMP或LNMP 本文以LAMP为基础 注意:ph ...
- 【TP3.2.3】addAll方法的坑
问题:做一个导入Excel到数据库的功能中需要用到addAll功能,但是每次执行到addAll()时都会报错,如下 Insert value list does not match column li ...
- Java面向对象系列(11)- instanceof和类型转换
instanceof 先看引用类型的类和instanceof比较的类有没有父子关系,有则可以编译,IDEA不报错 new一个对象,对象new所在的类和instanceof比较的类有没有父子关系,有则为 ...
- 如何解决SVN Upgrade working copy问题
电脑还原系统后,安装了最新版本的SVN,发现原来在svn检出的文件夹出现了SVN Upgrade working copy,没有commit ,没有update. 在网上查询到:出现这个的原因是因为你 ...
- 定要过python二级 第三套
第一模块 基础操作(共三道题) 1. 安装python 包 我在c 盘打开 但是它给我安装到了d盘得 anaconda3 下面 关键是 我在c盘 打开python .exe 创建 ...
