Spring Cloud Gateway Predicate.Path过滤分析

源码位置
spring-cloud-gateway-core-2.0.1.RELEASE-sources.jar!/org/springframework/cloud/gateway/handler/predicate/PathRoutePredicateFactory.java

过滤方法

    @Override
    public Predicate apply(Config config) {
        synchronized (this.pathPatternParser) {//仅在第一次调用路由时执行,将pattern字符串转PathPattern对象
            config.pathPattern = this.pathPatternParser.parse(config.pattern);
        }
        return exchange -> {
            PathContainer path = parsePath(exchange.getRequest().getURI().getPath());//path(url)转PathContainer对象   
//在此位置设置断点,每次走到需要predicate.Path过滤的路径都会进入到这里

            boolean match = config.pathPattern.matches(path);//路径表达式匹配判断
            traceMatch("Pattern", config.pathPattern.getPatternString(), path, match);
            if (match) {
                PathMatchInfo uriTemplateVariables = config.pathPattern.matchAndExtract(path);
                exchange.getAttributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVariables);
                return true;
            } else {
                return false;
            }
        };
    }

手动测试表达式效果
new PathPatternParser().parse("/sys*/**").matches(path)

匹配/sys-aaa/sadf、/sysf3s/sa等格式路径

 

进入逻辑:
onNext:reactor-core-3.1.10.RELEASE-sources.jar!/reactor/core/publisher/MonoFilterWhen.java
从这里进入gateway
lookupRoute:spring-cloud-gateway-core-2.0.1.RELEASE-sources.jar!/org/springframework/cloud/gateway/handler/RoutePredicateHandlerMapping.java
进入
toAsyncPredicate:spring-cloud-gateway-core-2.0.1.RELEASE-sources.jar!/org/springframework/cloud/gateway/support/ServerWebExchangeUtils.java
最后进入
lambda$apply$:spring-cloud-gateway-core-2.0.1.RELEASE-sources.jar!/org/springframework/cloud/gateway/handler/predicate/PathRoutePredicateFactory.java

你可能感兴趣的:(Spring,Cloud)