StripPrefix
过滤器
StripPrefix
过滤器接受一个参数,即 parts
。parts
参数指示在将请求发送到下游之前,要从请求路径中剥离的部分数量。以下清单配置了一个 StripPrefix
过滤器
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: strip_prefix_route
uri: https://example.org
predicates:
- Path=/name/**
filters:
- StripPrefix=2
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
@Configuration
class RouteConfiguration {
@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsStripPrefix() {
return route("strip_prefix_route")
.GET("/name/**", http())
.before(uri("https://example.org"))
.before(stripPrefix(2))
.build();
}
}
当通过网关向 /name/blue/red
发出请求时,完整的请求 URL 看起来像 example.org/red
。
如果使用 lb() 过滤器,它需要在 stripPrefix() 过滤器之后,否则生成的 URL 可能会不正确。配置中的 lb: Scheme 处理程序会自动将该过滤器置于最高优先级。 |