https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
GetewayFilter
GlobalFilter
SpringMVC =====> Spring WebFlux
DispatchServlet =====> DispatchHandler
路由匹配:
HandlerMapping =====>HandlerMapping
HanderAdaper ====> HanderAdaper
Hander =====> WebHander
- public Mono
handle(ServerWebExchange exchange) { - return this.handlerMappings == null ? this.createNotFoundError() : Flux.fromIterable(this.handlerMappings).concatMap((mapping) -> {
- return mapping.getHandler(exchange);
- }).next().switchIfEmpty(this.createNotFoundError()).flatMap((handler) -> {
- return this.invokeHandler(exchange, handler);
- }).flatMap((result) -> {
- return this.handleResult(exchange, result);
- });
- }
在lookupRoute执行所有的 Predicate断言
- protected Mono
lookupRoute(ServerWebExchange exchange) { - return this.routeLocator.getRoutes().concatMap((route) -> {
- return Mono.just(route).filterWhen((r) -> {
- exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR, r.getId());
- return (Publisher)r.getPredicate().apply(exchange);
- }).doOnError((e) -> {
- this.logger.error("Error applying predicate for route: " + route.getId(), e);
- }).onErrorResume((e) -> {
- return Mono.empty();
- });
- }).next().map((route) -> {
- if (this.logger.isDebugEnabled()) {
- this.logger.debug("Route matched: " + route.getId());
- }
-
- this.validateRoute(route, exchange);
- return route;
- });
- }
org.springframework.cloud.gateway.handler.FilteringWebHandler#handle
将所有的GlobalFilter 转换成Filter 加入到过滤器链中
- public Mono
handle(ServerWebExchange exchange) { - Route route = (Route)exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
- List
gatewayFilters = route.getFilters(); - List
combined = new ArrayList(this.globalFilters); - combined.addAll(gatewayFilters);
- AnnotationAwareOrderComparator.sort(combined);
- if (logger.isDebugEnabled()) {
- logger.debug("Sorted gatewayFilterFactories: " + combined);
- }
-
- return (new FilteringWebHandler.DefaultGatewayFilterChain(combined)).filter(exchange);
- }
所有的filter
ribbon 根据serviceId 找到对应服务的ip
- public Mono
handle(ServerWebExchange exchange) { - Route route = (Route)exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
- List
gatewayFilters = route.getFilters(); - List
combined = new ArrayList(this.globalFilters); - combined.addAll(gatewayFilters);
- AnnotationAwareOrderComparator.sort(combined);
- if (logger.isDebugEnabled()) {
- logger.debug("Sorted gatewayFilterFactories: " + combined);
- }
-
- return (new FilteringWebHandler.DefaultGatewayFilterChain(combined)).filter(exchange);
- }