SpringCloud-gateWay源码分析

1.Gateway的大概流程

1.首先前端请求被DispatcherHandler铺获拦截,然后执行handler方法进行URI解析
2.然后根据URI去调用HandlerMapping,获取真正的webHandler
3.然后选择一个对应的HandlerAdapter执行

1.1DispatcherHandler#handler

 public Mono<Void> handle(ServerWebExchange exchange) {
        return this.handlerMappings == null ? this.createNotFoundError() : 
        //1.handlerMappings有六个,遍历执行每一个mapping中的getHandler
        Flux.fromIterable(this.handlerMappings)
        .concatMap((mapping) -> 
        //2.执行mapping中的Handler方法,比较常用的为RequestMappingHandlerMapping,RoutePredicateHandlerMapping
        mapping.getHandler(exchange)).next().switchIfEmpty(this.createNotFoundError())
        //3.根据mapping.getHandler获取到对应的WebHandler,然后执行invokeHandler
        .flatMap((handler) -> this.invokeHandler(exchange, handler))
        .flatMap((result) -> this.handleResult(exchange, result));
    }

handlerMappings

WebFluxEndpointHandlerMapping
ControllerEndpointHandlerMapping
RouterFunctionMapping
RequestMappingHandlerMapping(常用的)
RoutePredicateHandlerMapping(常用的)
SimpleUrlHandlerMapping

1.2AbstractHandlerMapping#getHandler

public Mono<Object> getHandler(ServerWebExchange exchange) {
        //执行内部的handler方法,执行RequestMappingInfoHandlerMapping的和RoutePredicateHandlerMapping(重要)
        return this.getHandlerInternal(exchange).map((handler) -> {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug(exchange.getLogPrefix() + "Mapped to " + handler);
            }

            ServerHttpRequest request = exchange.getRequest();
            if (this.hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {
                CorsConfiguration config = this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(exchange) : null;
                CorsConfiguration handlerConfig = this.getCorsConfiguration(handler, exchange);
                config = config != null ? config.combine(handlerConfig) : handlerConfig;
                if (!this.corsProcessor.process(config, exchange) || CorsUtils.isPreFlightRequest(request)) {
                    return REQUEST_HANDLED_HANDLER;
                }
            }

            return handler;
        });
    }


      protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
        //配置文件配置的路由规则,遍历每一个,重要的是this.routeLocator.getRoutes()方法
        return this.routeLocator.getRoutes().concatMap((route) -> 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) -> Mono.empty())).next().map((route) -> {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Route matched: " + route.getId());
            }

            this.validateRoute(route, exchange);
            return route;
        });
    }

1.3RoutePredicateHandlerMapping#getHandlerInternal

protected Mono<?> getHandlerInternal(ServerWebExchange exchange) {
        if (this.managementPortType == RoutePredicateHandlerMapping.ManagementPortType.DIFFERENT && this.managementPort != null && exchange.getRequest().getURI().getPort() == this.managementPort) {
            return Mono.empty();
        } else {
            exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_HANDLER_MAPPER_ATTR, this.getSimpleName());
            return this.lookupRoute(exchange).flatMap((r) -> {
                exchange.getAttributes().remove(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Mapping [" + this.getExchangeDesc(exchange) + "] to " + r);
                }

                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, r);             
                //返回FilterWebHandler
                return Mono.just(this.webHandler);
            }).switchIfEmpty(Mono.empty().then(Mono.fromRunnable(() -> {
                exchange.getAttributes().remove(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
                if (this.logger.isTraceEnabled()) {
                    this.logger.trace("No RouteDefinition found for [" + this.getExchangeDesc(exchange) + "]");
                }

            })));
        }
    }

    protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
        //根据this.routeLocator.getRoutes()匹配到当前路由对应的断言处理器
        return this.routeLocator.getRoutes().concatMap((route) -> Mono.just(route).filterWhen((r) -> {
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR, r.getId());
                //执行断言的apply方法
                return (Publisher)r.getPredicate().apply(exchange);
            }).doOnError((e) -> this.logger.error("Error applying predicate for route: " + route.getId(), e)).onErrorResume((e) -> Mono.empty())).next().map((route) -> {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Route matched: " + route.getId());
            }

            this.validateRoute(route, exchange);
            return route;
        });
    }

1.3 RouteDefinitionRouteLocator#getRoutes()

    public Flux<Route> getRoutes() {
       //this.routeDefinitionLocator.getRouteDefinitions()拿到配置文件配置的路由规则,然后遍历执行convertToRoute方法
        Flux<Route> routes = this.routeDefinitionLocator.getRouteDefinitions().map(this::convertToRoute);
        if (!this.gatewayProperties.isFailOnRouteDefinitionError()) {
            routes = routes.onErrorContinue((error, obj) -> {
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("RouteDefinition id " + ((RouteDefinition)obj).getId() + " will be ignored. Definition has invalid configs, " + error.getMessage());
                }

            });
        }
     private Route convertToRoute(RouteDefinition routeDefinition) {
     //this.combinePredicates(routeDefinition)获取配置文件路由配置的(predicate )断言规则
        AsyncPredicate<ServerWebExchange> predicate = this.combinePredicates(routeDefinition);
        //获取所有的过滤器
        List<GatewayFilter> gatewayFilters = this.getFilters(routeDefinition);
        return ((Route.AsyncBuilder)Route.async(routeDefinition).asyncPredicate(predicate).replaceFilters(gatewayFilters)).build();
    }

    private AsyncPredicate<ServerWebExchange> combinePredicates(RouteDefinition routeDefinition) {
        //获取一个router中配置的断言规则
        List<PredicateDefinition> predicates = routeDefinition.getPredicates();
        if (predicates != null && !predicates.isEmpty()) {
           //执行this.lookup方法,参数是routeDefinition和配置的第一个断言规则
            AsyncPredicate<ServerWebExchange> predicate = this.lookup(routeDefinition, (PredicateDefinition)predicates.get(0));

            for(PredicateDefinition andPredicate : predicates.subList(1, predicates.size())) {
                AsyncPredicate<ServerWebExchange> found = this.lookup(routeDefinition, andPredicate);
                predicate = predicate.and(found);
            }

            return predicate;
        } else {
            return AsyncPredicate.from((exchange) -> true);
        }
    }

    private List<GatewayFilter> getFilters(RouteDefinition routeDefinition) {
        List<GatewayFilter> filters = new ArrayList();
        //默认过滤器属性不为空spring.cloud.gateway.default.filters
        if (!this.gatewayProperties.getDefaultFilters().isEmpty()) {
            //获取默认的过滤器加入到filters中
            filters.addAll(this.loadGatewayFilters("defaultFilters", new ArrayList(this.gatewayProperties.getDefaultFilters())));
        }
        //获取路由配置的过滤器,将默认的过滤器和路由配置的过滤器合并
        if (!routeDefinition.getFilters().isEmpty()) {
            filters.addAll(this.loadGatewayFilters(routeDefinition.getId(), new ArrayList(routeDefinition.getFilters())));
        }
        //根据Order排序,数字越小越在前面
        AnnotationAwareOrderComparator.sort(filters);
        return filters;
    }

    private AsyncPredicate<ServerWebExchange> lookup(RouteDefinition route, PredicateDefinition predicate) {
    //从内置的断言工厂中匹配到路由配置的断言工厂,内置的有十三个断言工厂
        RoutePredicateFactory<Object> factory = (RoutePredicateFactory)this.predicates.get(predicate.getName());
        if (factory == null) {
            throw new IllegalArgumentException("Unable to find RoutePredicateFactory with name " + predicate.getName());
        } else {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("RouteDefinition " + route.getId() + " applying " + predicate.getArgs() + " to " + predicate.getName());
            }
            //predicate.getName()为Path predicate.getArgs()为/order/**,
            //因为我配置的第一个路由规则为spring.cloud.gateway.routes[0].predicates[0]=Path=/order/**,然后发送一个PredicateArgsEvent事件
            Object config = ((ConfigurationService.ConfigurableBuilder)((ConfigurationService.ConfigurableBuilder)((ConfigurationService.ConfigurableBuilder)this.configurationService.with(factory).name(predicate.getName())).properties(predicate.getArgs())).eventFunction((bound, properties) -> new PredicateArgsEvent(this, route.getId(), properties))).bind();
            //执行PathRoutePredicateFactory#apply方法
            return factory.applyAsync(config);
        }
    }

在这里插入图片描述

1.4PathRoutePredicateFactory#apply

  public Predicate<ServerWebExchange> apply(final Config config) {
        final ArrayList<PathPattern> pathPatterns = new ArrayList();
        synchronized(this.pathPatternParser) {
            this.pathPatternParser.setMatchOptionalTrailingSeparator(config.isMatchOptionalTrailingSeparator());
            //config.getPatterns()为/order/**
            config.getPatterns().forEach((pattern) -> {
                PathPattern pathPattern = this.pathPatternParser.parse(pattern);
                pathPatterns.add(pathPattern);
            });
        }

        return new GatewayPredicate() {
            public boolean test(ServerWebExchange exchange) {
                PathContainer path = PathContainer.parsePath(exchange.getRequest().getURI().getRawPath());
                Optional<PathPattern> optionalPathPattern = pathPatterns.stream().filter((pattern) -> pattern.matches(path)).findFirst();
                if (optionalPathPattern.isPresent()) {
                    PathPattern pathPattern = (PathPattern)optionalPathPattern.get();
                    PathRoutePredicateFactory.traceMatch("Pattern", pathPattern.getPatternString(), path, true);
                    PathPattern.PathMatchInfo pathMatchInfo = pathPattern.matchAndExtract(path);
                    ServerWebExchangeUtils.putUriTemplateVariables(exchange, pathMatchInfo.getUriVariables());
                    return true;
                } else {
                    PathRoutePredicateFactory.traceMatch("Pattern", config.getPatterns(), path, false);
                    return false;
                }
            }

1.5.经过执返回FilterWebHandler,然后执行this.invokeHandler(exchange, handler)

 public Mono<Void> handle(ServerWebExchange exchange) {
        return this.handlerMappings == null ? 
        this.createNotFoundError() : Flux.fromIterable(this.handlerMappings)
        .concatMap((mapping) -> mapping.getHandler(exchange)).next()
        .switchIfEmpty(this.createNotFoundError())
        //执行过滤器逻辑
        .flatMap((handler) -> this.invokeHandler(exchange, handler))
        .flatMap((result) -> this.handleResult(exchange, result));
    }
    private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {
        if (this.handlerAdapters != null) {
            //handlerAdapters有三个,主要是SimpleHandlerAdapter
            for(HandlerAdapter handlerAdapter : this.handlerAdapters) {
                if (handlerAdapter.supports(handler)) {
                    //主要是SimpleHandlerAdapter
                    return handlerAdapter.handle(exchange, handler);
                }
            }
        }

        return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
    }

1.6SimpleHandlerAdapter#handle

    public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
        WebHandler webHandler = (WebHandler)handler;
        //webHandler主要为FilterWebHandler
        Mono<Void> mono = webHandler.handle(exchange);
        return mono.then(Mono.empty());
    }

1.7FilteringWebHandler#handle

    public Mono<Void> handle(ServerWebExchange exchange) {
        Route route = (Route)exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        //获取路由配置的过滤器
        List<GatewayFilter> gatewayFilters = route.getFilters();
        //全局过滤器
        List<GatewayFilter> combined = new ArrayList(this.globalFilters);
        //将过滤器合并排序
        combined.addAll(gatewayFilters);
        AnnotationAwareOrderComparator.sort(combined);
        if (logger.isDebugEnabled()) {
            logger.debug("Sorted gatewayFilterFactories: " + combined);
        }
        //构建责任链进行调用
        return (new DefaultGatewayFilterChain(combined)).filter(exchange);
    }

全局过滤器及其路由匹配的过滤器

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值