3.0.3 版本
术语
- Route: 网关的基本构成模块。它由 一个
ID
、一个目的地 URI、一个predicates
集合和一个filters
集合定义。 如果聚合谓词为真,则匹配路由。如果所有的predicates
是true
,那么Route
匹配。 - Predicate: java8的 一个接口,路由转发的判断条件,输入类型是 Spring 框架的
ServerWebExchange
接口类型。这使您可以匹配来自 HTTP 请求的任何内容,例如标头或参数。 - Filter:这些是使用特定工厂构建的
GatewayFilter
实例。在这里,您可以在发送下游请求之前或之后修改请求和响应。
Spring Cloud Gateway的处理流程
客户端向 Spring Cloud Gateway 发出请求。然后在 Gateway Handler Mapping
中找到与请求相匹配的路由,将其发送到 Gateway Web Handler
。Handler
再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。
配置Route Predicate Factories(路由断言工厂)和 Gateway Filter Factories(网关过滤器工厂)
有两种方法可以predicates
和 filters
:简化方式和完全扩展的参数。后者,本文不推荐,详见官网文档https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
简化方式
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- Cookie=mycookie,mycookievalue
各字段含义如下:
id:我们自定义的路由 ID,保持唯一
uri:目标服务地址
predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。
上面的示例使用两个参数定义了 Cookie
路由断言工厂,即 cookie 名称:mycookie 和匹配 mycookievalue 的值
Route Predicate Factories(路由断言工厂)
Spring Cloud Gateway 包含许多内置的路由断言工厂。这些断言分别匹配 HTTP 请求的不同属性。您可以将多个路由断言工厂用逻辑and
语句组合在一起。
The After Route Predicate Factory(路由后断言工厂)
The Before Route Predicate Factory(路由前断言工厂)
The Between Route Predicate Factory(路由间断言工厂)
The Cookie Route Predicate Factory(cookie路由断言工厂)
The Header Route Predicate Factory(请求头路由断言工厂)
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(权重路由断言工厂)
GatewayFilter Factories(网关过滤器工厂)
The AddRequestHeader GatewayFilter Factory
The AddRequestParameter GatewayFilter Factory
The AddResponseHeader GatewayFilter Factory
The DedupeResponseHeader GatewayFilter Factory
Spring Cloud CircuitBreaker GatewayFilter Factory
The FallbackHeaders GatewayFilter Factory
The MapRequestHeader GatewayFilter Factory
The PrefixPath GatewayFilter Factory
The PreserveHostHeader GatewayFilter Factory
The RequestRateLimiter GatewayFilter Factory
The RedirectTo GatewayFilter Factory
The RemoveRequestHeader GatewayFilter Factory
Global Filters
GlobalFilter
接口与 GatewayFilter
具有相同的签名。这些是有条件地应用于所有路由的特殊过滤器。
HttpHeadersFilters
HttpHeadersFilters 在向下游发送请求之前应用于请求,例如在 NettyRoutingFilter
中。
CORS Configuration
您可以配置网关以控制 CORS 行为。 “全局” CORS 配置是 URL 模式到 Spring 框架 CorsConfiguration
的映射。以下示例配置 CORS:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.spring.io"
allowedMethods:
- GET
在前面的示例中,对于所有 GET 请求路径,都允许来自 docs.spring.io
的请求发出 CORS 请求。
要为某些网关路由断言未处理的请求提供相同的 CORS 配置,请将 spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping
属性设置为 true
。当您尝试支持 CORS 预检请求并且您的路由断言由于 HTTP 方法是options
而未评估为 true
时,这很有用。