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的效果,而且功能更强大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值