Java 路由 API

Spring Cloud Gateway Server MVC 使用 Spring WebMvc.fn RouterFunctions.Builder 作為建立路由的預設方式,這些路由是 WebMvc.fn RouterFunction 實例。

RouterFunctions.Builder 實例可透過呼叫 RouterFunctions.route() 取得

GatewaySampleApplication.java
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();
    }
}

RouterFunctions.Builder 中有適用於每個 HTTP 方法 (GET、POST 等) 的方法,並結合路徑預測,例如上方的 /get。最後一個參數是 HandlerFilterFunction,在此案例中為 HandlerFunctions.http()。每個 HTTP 方法都有額外的 RequestPredicate 參數的過載方法,以及適用於一般用途的通用 route(RequestPredicate, HandlerFunction) 方法。

RouterFunctions.Builder 的閘道 MVC 實作

某些進階篩選器需要將一些中繼資料新增至請求屬性。為了容納此需求,有一個 org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions 類別。GatewayRouterFunctions.route(String routeId) 建立 RouterFunctions.Builder 實例,然後新增一個 'before' 篩選器,以將 routeId 新增為請求中繼資料。

GatewaySampleApplication.java
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();
    }
}

閘道 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