spring cloud gateway的stripPrefix配置

本文主要研究下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>.*), /$\{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<String> 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/(?<segment>.*),replacement是/${segment}

小结

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

上一篇:JavaSE(3)——Java当中的注释


下一篇:webapi中session为null的解决方案