跳到主要内容

Java 路由 API

DeepSeek V3 中英对照 Java Routes 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.handler.HandlerFunctions.http;

class SimpleGateway {
@Bean
public RouterFunction<ServerResponse> getRoute() {
return route().GET("/get", http("https://httpbin.org")).build();
}
}
java

RouterFunctions.Builder 中有对应于每个 HTTP 方法(GET、POST 等)的方法,这些方法可以与路径谓词结合使用,例如上面提到的 /get。最后一个参数是 HandlerFilterFunction,在这个例子中是 HandlerFunctions.http()。每个 HTTP 方法还有重载方法,用于额外的 RequestPredicate 参数,以及一个通用的 route(RequestPredicate, HandlerFunction) 方法,供一般使用。

Gateway MVC 实现的 RouterFunctions.Builder

一些高级过滤器需要向请求属性中添加一些元数据。为了适应这一点,有一个 org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions 类。GatewayRouterFunctions.route(String routeId) 创建一个 RouterFunctions.Builder 实例,然后添加一个 'before' 过滤器,将 routeId 作为请求元数据添加进去。

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("https://httpbin.org")).build();
}
}
java

网关 MVC 处理函数

各种 RouterFunctions.Builder 方法都需要一个 HandlerFunction<ServerResponse>。为了创建一个由 MVC 网关代理的路由,HandlerFunction 的实现被提供在 org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions 中。最基本的是 http() HandlerFunction。如果将 URI 作为参数提供,则该 URI 将用作发送 HTTP 请求的下游目标(如上面的示例所示)。如果没有传递参数,该函数会在 org.springframework.cloud.gateway.server.mvc.common.MvcUtils.GATEWAY_REQUEST_URL_ATTR 请求属性中查找 URI。这使得动态目标(如负载均衡)能够设置 URI