StripPrefix 过滤器
StripPrefix Filter
StripPrefix 过滤器接收一个参数 parts。parts 参数表示在将请求发送到下游之前,从请求路径中剥离的部分数量。以下配置展示了如何配置 StripPrefix 过滤器:
spring:
cloud:
gateway:
server:
webmvc:
routes:
- id: strip_prefix_route
uri: https://example.org
predicates:
- Path=/name/**
filters:
- StripPrefix=2
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](https://example.org/red)。
注意
如果使用 lb() 过滤器,需要将其放在 stripPrefix() 过滤器之后,否则生成的 URL 可能不正确。配置中的 lb: 方案处理程序会自动将该过滤器置于最高优先级顺序。