Spring 云网关 - 去除前缀(如果存在)
Spring Cloud Gateway - strip prefix if exists
我需要 Spring Cloud Gateway 根据 Host
header 或路径前缀将请求路由到微服务。在任何情况下,路径前缀都必须从路径中删除,但前提是已设置。
我想出了下面的代码,我只认为 "sip" 是一个前缀:
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.host("sip")
.or()
.path("/sip/**")
.filters(f -> f.stripPrefix(1))
.uri("http://sip:8080")
)
.build();
}
问题是 Spring 删除了路径的第一段,即使它不是前缀。
例如,具有路径 /sip/calls
的请求成功,但具有主机 header 集的 /calls
没有成功,因为 Spring 认为 /calls
前缀并将其删除,这会导致空路径。 /calls/calls
具有 Host
header 的路径成功,因为 Spring 仅删除第一个 calls
路径段。
如何同时使用主机和路径,仅在匹配定义值时才删除前缀?
ps 我在考虑每个服务两条路线,但它看起来不太好,虽然它实现了目标:
.route(r -> r.header("Host", "form").uri("http://form:8080"))
.route(r -> r.path("/form/**")
.filters(f -> f.stripPrefix(1))
.uri("http://form:8080"))
你可以这样做
.route(r -> r.host("sip")
.or()
.path("/sip/**")
.filters(f -> f.rewritePath("^/sip", ""))
.uri("http://sip:8080")
删除行为是正常的,您可以为 /calls 使用另一个路由,并且对于该路由,您不添加删除前缀子句。
官方文档:https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-stripprefix-gatewayfilter-factory
我需要 Spring Cloud Gateway 根据 Host
header 或路径前缀将请求路由到微服务。在任何情况下,路径前缀都必须从路径中删除,但前提是已设置。
我想出了下面的代码,我只认为 "sip" 是一个前缀:
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.host("sip")
.or()
.path("/sip/**")
.filters(f -> f.stripPrefix(1))
.uri("http://sip:8080")
)
.build();
}
问题是 Spring 删除了路径的第一段,即使它不是前缀。
例如,具有路径 /sip/calls
的请求成功,但具有主机 header 集的 /calls
没有成功,因为 Spring 认为 /calls
前缀并将其删除,这会导致空路径。 /calls/calls
具有 Host
header 的路径成功,因为 Spring 仅删除第一个 calls
路径段。
如何同时使用主机和路径,仅在匹配定义值时才删除前缀?
ps 我在考虑每个服务两条路线,但它看起来不太好,虽然它实现了目标:
.route(r -> r.header("Host", "form").uri("http://form:8080"))
.route(r -> r.path("/form/**")
.filters(f -> f.stripPrefix(1))
.uri("http://form:8080"))
你可以这样做
.route(r -> r.host("sip")
.or()
.path("/sip/**")
.filters(f -> f.rewritePath("^/sip", ""))
.uri("http://sip:8080")
删除行为是正常的,您可以为 /calls 使用另一个路由,并且对于该路由,您不添加删除前缀子句。
官方文档:https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-stripprefix-gatewayfilter-factory