spring cloud gateway的stripPrefix配置

2018-02-27 11:49:02来源:oschina作者:go4it人点击

分享

本文主要研究下spring cloud gateway的stripPrefix配置


使用zuul的配置
zuul:
routes:
demo:
sensitiveHeaders: Access-Control-Allow-Origin,Access-Control-Allow-Methods
path: /demo/**
stripPrefix: true
url: http://demo.com.cn/

这里的stripPrefix默认为true,也就是所有/demo/xxxx的请求转发给http://demo.com.cn/xxxx ,去除掉demo前缀



使用spring cloud gateway的配置
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
routes:
- id: demo
uri: http://demo.com.cn:80
order: 8999 ## 越小越优先
predicates:
- Path=/demo/**
filters:
- RewritePath=/demo/(?.*), /$/{segment}

spring cloud gateway貌似没有现成的stripPrefix的配置,不过可以通过rewritepath来实现



spring-cloud-gateway-core-2.0.0.M6-sources.jar!/org/springframework/cloud/gateway/filter/factory/RewritePathGatewayFilterFactory.java


public class RewritePathGatewayFilterFactory implements GatewayFilterFactory {
public static final String REGEXP_KEY = "regexp";
public static final String REPLACEMENT_KEY = "replacement";
@Override
public List argNames() {
return Arrays.asList(REGEXP_KEY, REPLACEMENT_KEY);
}
@Override
public GatewayFilter apply(Tuple args) {
final String regex = args.getString(REGEXP_KEY);
String replacement = args.getString(REPLACEMENT_KEY).replace("$//", "$");
return apply(regex, replacement);
}
public GatewayFilter apply(String regex, String replacement) {
return (exchange, chain) -> {
ServerHttpRequest req = exchange.getRequest();
addOriginalRequestUrl(exchange, req.getURI());
String path = req.getURI().getPath();
String newPath = path.replaceAll(regex, replacement);
ServerHttpRequest request = mutate(req)
.path(newPath)
.build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
return chain.filter(exchange.mutate().request(request).build());
};
}
}

主要是这段String newPath = path.replaceAll(regex, replacement),这里相当于regex是/demo/(?.*),replacement是/${segment}



小结

spring cloud gateway利用RewritePath可以实现原来的zuul的stripPrefix的效果,而且功能更强大。


doc
rewritepath_gatewayfilter_factory

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台