SetPath 过滤器
SetPath Filter
SetPath 过滤器接收一个路径 template 参数。它提供了一种简单的方式来操作请求路径,允许使用路径的模板化片段。这使用了 Spring Framework 中的 URI 模板。允许多个匹配片段。以下示例配置了一个 SetPath 过滤器:
spring:
cloud:
gateway:
server:
webmvc:
routes:
- id: setpath_route
uri: https://example.org
predicates:
- Path=/red/{segment}
filters:
- SetPath=/{segment}
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: 方案处理器会自动将该过滤器置于最高优先级顺序。