SetPath
过滤器
SetPath
过滤器接受一个 path template
参数。它通过允许路径中的模板化片段来简单地操作请求路径。这使用了 Spring Framework 中的 URI 模板。允许匹配多个片段。以下示例配置了 SetPath
过滤器:
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: setpath_route
uri: https://example.org
predicates:
- Path=/red/{segment}
filters:
- SetPath=/{segment}
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.setPath;
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> gatewayRouterFunctionsSetPath() {
return route("setpath_route")
.GET("/red/{segment}", http())
.before(uri("https://example.org"))
.before(setPath("/{segment"))
.build();
}
}
对于请求路径 /red/blue
,这会将路径设置为 /blue
,然后再进行下游请求。
如果使用 lb() 过滤器,它需要放在 setPath() 过滤器之后,否则生成的 URL 可能不正确。配置中的 lb: scheme handler 会自动将该过滤器放在最高优先级。 |