Spring Cloud Gateway 源码剖析之Predicate谓词详解

本文详细介绍了Spring Cloud Gateway中多种Route匹配Predicate的实现,包括CookieRoutePredicateFactory、HeaderRoutePredicateFactory、HostRoutePredicateFactory、MethodRoutePredicateFactory、PathRoutePredicateFactory、QueryRoutePredicateFactory、RemoteAddrRoutePredicateFactory。通过源码分析,阐述了如何根据请求的Cookie、Header、Host、Method、Path、QueryParam和远程地址进行路由匹配。
摘要由CSDN通过智能技术生成

} else {

Iterator var3 = cookies.iterator();

HttpCookie cookie;

do {

if (!var3.hasNext()) {

return false;

}

cookie = (HttpCookie)var3.next();

} while(!cookie.getValue().matches(config.regexp));

return true;

}

};

}

2.5 HeaderRoutePredicateFactory

  • Route 匹配 :请求头满足匹配

  • 配置:

spring:

cloud:

gateway:

routes:

  • id: header_route

uri: http://example.org

predicates:

  • Header=X-Request-Id, \d+
  • 代码:

public Predicate apply(HeaderRoutePredicateFactory.Config config) {

boolean hasRegex = !StringUtils.isEmpty(config.regexp);

return (exchange) -> {

List values = (List)exchange.getRequest().getHeaders().getOrDefault(config.header, Collections.emptyList());

if (values.isEmpty()) {

return false;

} else {

return hasRegex ? values.stream().anyMatch((value) -> {

return value.matches(config.regexp);

}) : true;

}

};

}

2.6 HostRoutePredicateFactory

  • Route 匹配 :请求 Host 匹配指定值

  • 配置:

spring:

cloud:

gateway:

routes:

  • id: host_route

uri: http://example.org

predicates:

  • Host=**.somehost.org
  • 代码:

public Predicate apply(HostRoutePredicateFactory.Config config) {

return (exchange) -> {

String host = exchange.getRequest().getHeaders().getFirst(“Host”);

Optional optionalPattern = config.getPatterns().stream().filter((pattern) -> {

return this.pathMatcher.match(pattern, host);

}).findFirst();

if (optionalPattern.isPresent()) {

Map<String, String> variables = this.pathMatcher.extractUriTemplateVariables((String)optionalPattern.get(), host);

ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);

return true;

} else {

return false;

}

};

}

2.7 MethodRoutePredicateFactory

  • Route 匹配 :请求 Method 匹配指定值

  • 配置:

spring:

cloud:

gateway:

routes:

  • id: method_route

uri: http://example.o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值