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 會自動將該過濾器放在最高優先順序。