专业的JAVA编程教程与资源

网站首页 > java教程 正文

Spring Cloud Gateway的路由断言(Predicate)-Part 2

temp10 2024-11-05 11:53:39 java教程 19 ℃ 0 评论

Spring Cloud Gateway的路由匹配的功能是以 Spring WebFlux中的Handler Mapping为基础实现的。

Spring Cloud Gateway 创建 Route 对象时, 使用 RoutePredicateFactory 创建 Predicate 对象,Predicate 对象可以赋值给 Route。 Spring Cloud Gateway 包含许多内置的Route Predicate Factories。所有这些断言都匹配HTTP请求的不同属性。多种断言工厂可以组合,并通过逻辑and。

Spring Cloud Gateway的路由断言(Predicate)-Part 2

路由选择是通过Predicate函数式接口进行判断当前路由是否满足给定条件。匹配成功则进行转发,否则处理失败。


路由断言工厂 RoutePredicateFactory

路由断言工厂 RoutePredicateFactory 包含的主要实现类如图所示,可以看到该接口有多个实现类。

抽象类 AbstractRoutePredicateFactory 实现了路由断言工厂,但是没有实际的方法,具体的实现类都是继承自抽象类 AbstractRoutePredicateFactory 包括 Datetime、 请求的远端地址、 路由权重、 请求头、 Host 地址、 请求方法、 请求路径和请求参数等类型的路由断言。



下面以Query路由断言工厂(QueryRouteRedicateFactory)为示例,演示Spring Cloud Gateway路由断言的具体使用。


1. 引用gateway的jar包依赖。

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-gateway</artifactId>

</dependency>


2. 使用Java代码自定义RouteLocator的配置。

在启动类Application配置网关路由,如下所示,定义bean对象。


上述代码,也可以使用属性文件的配置方式,如在application.yml 中配置(二选一即可)。

spring:

cloud:

gateway:

routes:

- id: query_route

uri: http://baidu.com

predicates:

- Query=name, rickie


3. 启动演示项目

演示项目中的application.yml 配置参数如下。

访问 http://localhost:8080/?name=rickie,就会成功转发到对应的uri,因为断言匹配成功。


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表