Java 路由 API
Spring Cloud Gateway Server MVC 使用 Spring WebMvc.fn RouterFunctions.Builder
作为创建路由的默认方式,这些路由是 WebMvc.fn RouterFunction
实例。
通过调用 RouterFunctions.route()
获取一个 RouterFunctions.Builder
实例
import static org.springframework.web.servlet.function.RouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
class SimpleGateway {
@Bean
public RouterFunction<ServerResponse> getRoute() {
return route().GET("/get", http())
.before(uri("https://example.org"))
.build();
}
}
RouterFunctions.Builder
中有针对每个 HTTP 方法(GET、POST 等)与路径谓词(如上面的 /get
)组合的方法。最后一个参数是 HandlerFilterFunction
,在此示例中是 HandlerFunctions.http()
。对于额外的 RequestPredicate
参数,以及用于一般用途的通用 route(RequestPredicate, HandlerFunction
) 方法,每个 HTTP 方法都有重载方法。
RouterFunctions.Builder 的 Gateway MVC 实现
一些高级过滤器需要将一些元数据添加到请求属性中。为了适应这一点,存在一个 org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions
类。GatewayRouterFunctions.route(String routeId)
创建一个 RouterFunctions.Builder
实例,然后添加一个 'before' 过滤器,将 routeId
添加为请求元数据。
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;
class SimpleGateway {
@Bean
public RouterFunction<ServerResponse> getRoute() {
return route("simple_route").GET("/get", http())
.before(uri("https://example.org"))
.build();
}
}
Gateway MVC Handler Functions
各种 RouterFunctions.Builder
方法需要一个 HandlerFunction<ServerResponse>
。为了创建由 MVC 网关代理的路由,org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions
中提供了 HandlerFunction
实现。最基本的是 http()
HandlerFunction
。该函数会在 org.springframework.cloud.gateway.server.mvc.common.MvcUtils.GATEWAY_REQUEST_URL_ATTR
请求属性中查找 URI
。这允许动态目标(例如负载均衡)设置 URI
。
从 4.1.7 版本开始,HandlerFunctions.http(String) 和 HandlerFunctions.http(URI) 已被弃用。请改用 HandlerFunctions.http() 与 BeforeFilterFunctions.uri() 过滤器组合的方式。这解决了处理路由 url 请求属性时的一致性问题。 |