springcloudgateway的stripPrefix配置
序
本⽂主要研究下spring cloud gateway的stripPrefix配置
使⽤zuul的配置
zuul:
routes:
demo:
sensitiveHeaders: Access-Control-Allow-Origin,Access-Control-Allow-Methods
path: /demo/**
stripPrefix: true
url: demo/
使⽤spring cloud gateway的配置
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
routes:
- id: demo
uri: demo: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";
spring framework jar包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 = String(REGEXP_KEY);
String replacement = String(REPLACEMENT_KEY).replace("$\\", "$");
return apply(regex, replacement);
}
public GatewayFilter apply(String regex, String replacement) {
return (exchange, chain) -> {
ServerHttpRequest req = Request();
addOriginalRequestUrl(exchange, URI());
String path = URI().getPath();
String newPath = placeAll(regex, replacement);
ServerHttpRequest request = mutate(req)
.path(newPath)
.build();
return chain.filter(exchange.mutate().request(request).build());
};
}
}
主要是这段String newPath = placeAll(regex, replacement),这⾥相当于regex是/demo/(?<segment>.*),replacement 是/${segment}
⼩结
spring cloud gateway利⽤RewritePath可以实现原来的zuul的stripPrefix的效果,⽽且功能更强⼤。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论