Spring Cloud Alibaba - 25 Gateway-路由断言工厂Route Predicate Factories谓词工厂示例及源码解析
文章目录
- 官网
- The After Route Predicate Factory
- 小栗子
- AfterRoutePredicateFactory源码
- The Before Route Predicate Factory
- 小栗子
- BeforeRoutePredicateFactory源码
- The Between Route Predicate Factory
- 小栗子
- BetweenRoutePredicateFactory源码
- The Cookie Route Predicate Factory
- 小栗子
- CookieRoutePredicateFactory源码
- The Header Route Predicate Factory
- 小栗子
- HeaderRoutePredicateFactory源码
- The Host Route Predicate Factory
- The Method Route Predicate Factory
- The Path Route Predicate Factory
- The Query Route Predicate Factory
- The RemoteAddr Route Predicate Factory
- The Weight Route Predicate Factory
- 源码
官网
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
Spring Cloud Gateway 将路由匹配为 Spring WebFluxHandlerMapping
基础架构的一部分。Spring Cloud Gateway 包含许多内置的路由谓词工厂。所有这些谓词都匹配 HTTP 请求的不同属性。我们可以将多个路由谓词工厂与逻辑and语句结合起来。
The After Route Predicate Factory
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-after-route-predicate-factory
小栗子
我们还是继续老工程 ,启动
artisan-cloud-gateway 【8888】
artisan-cloud-gateway-order
artisan-cloud-gateway-product
【网关配置】
application-after_route.yml
# 网关的After谓词,对应的源码处理AfterRoutePredicateFactory
#作用: 经过网关的所有请求 当前时间>比After阈值 就进行转发
#现在我们是2022年了 currentTime<After阈值,所以网关不会进行转发,而返回404spring:
spring:cloud:gateway: #gatewayroutes:- id: after_route # id 确保唯一uri: lb://artisan-cloud-gateway-order # nacos上的 注册地址predicates:- After=2025-02-13T18:27:28.309+08:00[Asia/Shanghai]
currentTime<After阈值,所以网关不会进行转发 .
激活配置文件
【测试】
符合预期。
如果我们改下时间呢?
AfterRoutePredicateFactory源码
public class AfterRoutePredicateFactoryextends AbstractRoutePredicateFactory<AfterRoutePredicateFactory.Config> {/*** DateTime key.*/public static final String DATETIME_KEY = "datetime";public AfterRoutePredicateFactory() {super(Config.class);}@Overridepublic List<String> shortcutFieldOrder() {return Collections.singletonList(DATETIME_KEY);}@Overridepublic Predicate<ServerWebExchange> apply(Config config) {return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange serverWebExchange) {final ZonedDateTime now = ZonedDateTime.now();return now.isAfter(config.getDatetime());}@Overridepublic String toString() {return String.format("After: %s", config.getDatetime());}};}public static class Config {@NotNullprivate ZonedDateTime datetime;public ZonedDateTime getDatetime() {return datetime;}public void setDatetime(ZonedDateTime datetime) {this.datetime = datetime;}}}
核心方法,apply,比较简单。
The Before Route Predicate Factory
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-before-route-predicate-factory
小栗子
application-before_route.yml
#目的:测试网关的Before谓词,对应的源码处理BeforeRoutePredicateFactory
#作用: 经过网关的所有请求当前时间 比Before=2021-02-13T18:27:28.309+08:00[Asia/Shanghai] 小 就进行转发
#现在2022年了 时间比配置的阈值大,所以我们不会进行转发,而返回404
#2021-02-13T18:27:28.309+08:00[Asia/Shanghai] 这个时间怎么获取的呢? --- System.out.println(ZonedDateTime.now())
spring:cloud:gateway: #gatewayroutes:- id: before_route # id 确保唯一uri: lb://artisan-cloud-gateway-orderpredicates:- Before=2023-02-13T18:27:28.309+08:00[Asia/Shanghai]
BeforeRoutePredicateFactory源码
public class BeforeRoutePredicateFactoryextends AbstractRoutePredicateFactory<BeforeRoutePredicateFactory.Config> {/*** DateTime key.*/public static final String DATETIME_KEY = "datetime";public BeforeRoutePredicateFactory() {super(Config.class);}@Overridepublic List<String> shortcutFieldOrder() {return Collections.singletonList(DATETIME_KEY);}@Overridepublic Predicate<ServerWebExchange> apply(Config config) {return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange serverWebExchange) {final ZonedDateTime now = ZonedDateTime.now();return now.isBefore(config.getDatetime());}@Overridepublic String toString() {return String.format("Before: %s", config.getDatetime());}};}public static class Config {private ZonedDateTime datetime;public ZonedDateTime getDatetime() {return datetime;}public void setDatetime(ZonedDateTime datetime) {this.datetime = datetime;}}}
The Between Route Predicate Factory
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-between-route-predicate-factory
小栗子
application-between-route.yml
# Between谓词 BetweenRoutePredicateFactory
# 就是经过网关请求的当前时间 currentTime 满足
# Between startTime < currentTime < Between EndTime 才进行转发
spring:cloud:gateway:routes:- id: between-route #id必须要唯一uri: lb://artisan-cloud-gateway-order # 这里可以使用负载均衡的写法predicates:- Between=2020-02-13T18:27:28.309+08:00[Asia/Shanghai],2025-02-13T18:27:28.309+08:00[Asia/Shanghai]
BetweenRoutePredicateFactory源码
public class BetweenRoutePredicateFactoryextends AbstractRoutePredicateFactory<BetweenRoutePredicateFactory.Config> {/*** DateTime 1 key.*/public static final String DATETIME1_KEY = "datetime1";/*** DateTime 2 key.*/public static final String DATETIME2_KEY = "datetime2";public BetweenRoutePredicateFactory() {super(Config.class);}@Overridepublic List<String> shortcutFieldOrder() {return Arrays.asList(DATETIME1_KEY, DATETIME2_KEY);}@Overridepublic Predicate<ServerWebExchange> apply(Config config) {Assert.isTrue(config.getDatetime1().isBefore(config.getDatetime2()),config.getDatetime1() + " must be before " + config.getDatetime2());return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange serverWebExchange) {final ZonedDateTime now = ZonedDateTime.now();return now.isAfter(config.getDatetime1())&& now.isBefore(config.getDatetime2());}@Overridepublic String toString() {return String.format("Between: %s and %s", config.getDatetime1(),config.getDatetime2());}};}@Validatedpublic static class Config {@NotNullprivate ZonedDateTime datetime1;@NotNullprivate ZonedDateTime datetime2;public ZonedDateTime getDatetime1() {return datetime1;}public Config setDatetime1(ZonedDateTime datetime1) {this.datetime1 = datetime1;return this;}public ZonedDateTime getDatetime2() {return datetime2;}public Config setDatetime2(ZonedDateTime datetime2) {this.datetime2 = datetime2;return this;}}}
The Cookie Route Predicate Factory
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-cookie-route-predicate-factory
小栗子
application-cookie-route.yml
#谓词 Cookie 源码 CookieRoutePredicateFactory
#表示通过网关的请求 必须带入包含了Cookie name=Company value=Artisan
#才转发请求
spring:cloud:gateway:routes:- id: cookie-route #id必须要唯一uri: lb://artisan-cloud-gateway-order # 这里可以使用负载均衡的写法predicates:#当我们的请求中包含了Cookie name=Company value=Artisan#才转发请求- Cookie=Company,Artisan
CookieRoutePredicateFactory源码
核心方法
@Overridepublic Predicate<ServerWebExchange> apply(Config config) {return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange exchange) {List<HttpCookie> cookies = exchange.getRequest().getCookies().get(config.name);if (cookies == null) {return false;}for (HttpCookie cookie : cookies) {if (cookie.getValue().matches(config.regexp)) {return true;}}return false;}@Overridepublic String toString() {return String.format("Cookie: name=%s regexp=%s", config.name,config.regexp);}};}
The Header Route Predicate Factory
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-header-route-predicate-factory
小栗子
application-header-route.yml
#Header谓词 源码HeaderRoutePredicateFactory
#说明请求经过网关 必须带入
#header的k=X-Request-appId v=Artisan才会被转发
spring:cloud:gateway:routes:- id: header-route #id必须要唯一uri: lb://artisan-cloud-gateway-orderpredicates:- Header=X-Request-appId,Artisan
HeaderRoutePredicateFactory源码
@Overridepublic Predicate<ServerWebExchange> apply(Config config) {boolean hasRegex = !StringUtils.isEmpty(config.regexp);return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange exchange) {List<String> values = exchange.getRequest().getHeaders().getOrDefault(config.header, Collections.emptyList());if (values.isEmpty()) {return false;}// values is now guaranteed to not be emptyif (hasRegex) {// check if a header value matchesreturn values.stream().anyMatch(value -> value.matches(config.regexp));}// there is a value and since regexp is empty, we only check existence.return true;}@Overridepublic String toString() {return String.format("Header: %s regexp=%s", config.header,config.regexp);}};}
The Host Route Predicate Factory
#Host谓词 源码HostRoutePredicateFactory
#说明请求http://localhost:8888/selectOrderInfoById/1的
#Host必须满足www.artisan.com:8888或者localhost:8888才会
#转发到http://artisan-cloud-gateway-order/selectOrderInfoById/1#而127.0.0.1不会被转发
spring:cloud:gateway:routes:- id: host-route #id必须要唯一uri: lb://artisan-cloud-gateway-orderpredicates:- Host=www.artisan.com:8888,localhost:8888
The Method Route Predicate Factory
#Http请求方法的谓词 Method 源码 MethodRoutePredicateFactory
#表示经过网关的请求 只有post方式才能被转发
spring:cloud:gateway:routes:- id: method #id必须要唯一uri: lb://artisan-cloud-gateway-orderpredicates:#当前请求的方式 http://localhost:8888/selectOrderInfoById/1 是Post才会被转发#到http://artisan-cloud-gateway-order/selectOrderInfoById/1- Method=Post
The Path Route Predicate Factory
The Query Route Predicate Factory
The RemoteAddr Route Predicate Factory
The Weight Route Predicate Factory
源码
https://github.com/yangshangwei/SpringCloudAlibabMaster
Spring Cloud Alibaba - 25 Gateway-路由断言工厂Route Predicate Factories谓词工厂示例及源码解析相关推荐
- 【Spring Cloud Alibaba】Gateway 服务网关
[Spring Cloud Alibaba]Gateway 服务网关 1 架构图 2 Predicate 断言 3 路由 3.1 静态路由 3.2 动态路由 3.3 Nacos 配置 4 过滤器 4. ...
- Spring Cloud Alibaba 集成 Gateway 实现动态路由功能
文章目录 1 摘要 2 核心 Maven 依赖 3 名词释义 4 Gateway 动态路由原理 5 数据库表 6 核心代码 6.1 配置信息 6.2 路由实体类 6.3 本地路由数据库持久层(DAO/ ...
- Spring Cloud Alibaba - 23 Gateway初体验
文章目录 概述 网关的作用 官网 来个栗子 step1 搞依赖 step2 搞注解 (gateway没有注解) step3 搞配置 其他工程 & 验证 参数解读 spring.cloud.ga ...
- Spring Cloud Alibaba - 27 Gateway源码解析
文章目录 How it works 入口 自动配置类源码分析 How it works https://docs.spring.io/spring-cloud-gateway/docs/current ...
- Spring Cloud Alibaba gateway ribbon 自定义负载均衡规则。发散灰度发布,金丝雀测试等
上一篇介绍了,ribbon的组件.本篇要自己写一个灰度方案.其实就是一个很简单的思维扩散. 需求 前端header请求携带version字段.路由服务根据version去需要对应版本的服务集合,进行或 ...
- Spring Cloud Alibaba 快速入门(七):Gateway微服务网关
前言:在微服务架构中,有一个组件可以说是必不可少的,那就是微服务网关.微服务网关处理了路由转发,负载均衡,缓存,权限校验,监控,限流控制,日志等.Spring Cloud Gateway是Spring ...
- Spring Cloud Alibaba - Gateway 入门案例(二)(Gateway 整合 nacos /(非阿里组件))
Spring Cloud Alibaba - Gateway 入门案例(二)(Gateway 整合 nacos)(非阿里组件) 回溯 Gateway 整合 nacos 方式一(复杂/灵活/常用) 方式 ...
- 【Spring Cloud Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间这里只贴出关键部分代码的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证 ...
- 从0到1手把手搭建spring cloud alibaba 微服务大型应用框架(十五) swagger篇 : gateway 集成swagger 与 knife4j实现在线api文档并嵌入到自己项目内
背景 我们日常开发中基本都是协同开发的,当然极个别的项目整体前后端都是一个人开发的,当多人协作时,尤其是前后端人员协同开发时 必然会面临着前端需要了解后端api接口的情况,两个选择,提前设计好文档,然 ...
最新文章
- 《将要淘汰的八种人》读后感
- CSS之布局(盒子模型--内边距)
- 链表问题3——删除链表的中间节点(初阶)
- 利用openfiler建立仲裁磁盘
- Ural 1018 (树形DP+背包+优化)
- 多大、谷歌大脑获ICML 2021杰出论文奖,田渊栋、陆昱成获荣誉提名!
- thinkbook14 2021款的一些坑
- NFS 网络挂载问题 解决
- 【学术相关】TopPaper:AI 初学者经典论文列表
- SqlParameter的作用与用法
- c语言将一个实型变量f=55.5678,《C语言程序设计》第2章2 常量和变量
- webStorm关闭自动保存
- 网摘Android调用WebService
- Windows常用运行库--VC++、DirectX、.NET
- 关于苹果手机页面中字体大小显示不正确的问题
- vue中computer和watch的区别和使用
- 2-2.基金的投资交易与结算
- HDU 1224 DFS
- 【一日一logo|day_8】坦格利安家族?修改什么的不存在的
- VB中的界面设计原则和编程技巧