1.Gateway概念介绍
网关的主要功能职责主要有 请求集中接入,多业务聚合,中介策略。gateway的中文翻译是 出入口的意思,其实该模块的职责其实超出了名字的含义,因为也包含了采用各种策略保户后端资源的可用性,所以我更想叫它 survival gateway。
网关分类如下:
2.Spring Cloud Gateway 架构梳理
Spring Cloud Gateway is built on Spring Boot 2.x, Spring WebFlux, and Project Reactor.
思考
1:gateway是如何被初始化的?
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore({ HttpHandlerAutoConfiguration.class,
WebFluxAutoConfiguration.class })
@AutoConfigureAfter({ GatewayLoadBalancerClientAutoConfiguration.class,
GatewayClassPathWarningAutoConfiguration.class })
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {
2:gateway如何嵌入请求链路中的?
3:gatway 如何设计各个组件的关系的,然后变得更加容易扩展
4:filter是如何执行的?
When a request matches a route, the filtering web handler adds all instances of GlobalFilter
and all route-specific instances of GatewayFilter
to a filter chain. This combined filter chain is sorted by the org.springframework.core.Ordered
interface, which you can set by implementing the getOrder()
method.
As Spring Cloud Gateway distinguishes between “pre” and “post” phases for filter logic execution (see How it Works), the filter with the highest precedence is the first in the “pre”-phase and the last in the “post”-phase. (GlobalFilter
会适配成 GatewayFilter
接口,然后放到 combined filter 集合中,然后按照 order 排序,进行执行)
3.Spring Cloud Gateway 组件介绍
3.1 Route: The basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates, and a collection of filters. A route is matched if the aggregate predicate is true.
public class Route implements Ordered {
private final String id;
private final URI uri;
private final int order;
//一组断言
private final AsyncPredicate<ServerWebExchange> predicate;
//一组filter
private final List<GatewayFilter> gatewayFilters;
//元数据
private final Map<String, Object> metadata;
}
3.2. Predicate(断言): This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange
. This lets you match on anything from the HTTP request, such as headers or parameters. (因为可以定义一组Route,所以需要断言进行匹配到某一个Route。)
3.3 Filter: These are instances of Spring Framework GatewayFilter
that have been constructed with a specific factory. Here, you can modify requests and responses before or after sending the downstream request. (可以在处理前后做点手脚和AOP一样), 其中filter 分成 gloable filter 和 gateway filter, 其中全局filter 不管匹配到那个Router都会按照某种条件执行。
目前支持的 gateway filter: https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#gatewayfilter-factories
gloable filter : https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#global-filters
4.Spring Cloud Gateway 自定义(断言/gateway filter/ gloable filter)扩展Demo
Github 地址: https://github.com/zhaoliuzeng/spring-cloud-gateway-226.git (后续完善)