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: 方案处理程序会自动将过滤器置于最高优先级。 |