PrefixPath 过滤器

PrefixPath 过滤器接受一个单独的 prefix 参数。以下示例配置了一个 PrefixPath 过滤器

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: prefixpath_route
          uri: https://example.org
          predicates:
          - Path=/**
          filters:
          - PrefixPath=/mypath
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.prefixPath;
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> gatewayRouterFunctionsPrefixPath() {
        return route("prefixpath_route")
            .GET("/**", http())
            .before(uri("https://example.org"))
            .before(prefixPath("/mypath"))
            .build();
    }
}

这会将 `/mypath` 作为前缀添加到所有匹配请求的路径中。因此,对 `/hello` 的请求将被发送到 `/mypath/hello`。

如果使用 lb() 过滤器,它需要放在 prefixPath() 过滤器之后,否则生成的 URL 可能不正确。配置中的 lb: 方案处理器会自动将该过滤器放在最高优先级的顺序。