CacheRequestBody GatewayFilter 工廠

某些情況下,需要讀取請求 body。由於請求只能讀取一次,我們需要快取請求 body。您可以使用 CacheRequestBody 篩選器來快取請求 body,然後再將其傳送到下游並從 exchange 屬性取得 body。

以下列表顯示如何快取請求 body GatewayFilter

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("cache_request_body_route", r -> r.path("/downstream/**")
            .filters(f -> f.prefixPath("/httpbin")
        		.cacheRequestBody(String.class).uri(uri))
        .build();
}
application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: cache_request_body_route
        uri: lb://downstream
        predicates:
        - Path=/downstream/**
        filters:
        - name: CacheRequestBody
          args:
            bodyClass: java.lang.String

CacheRequestBody 提取請求 body 並將其轉換為 body 類別 (例如,前面範例中定義的 java.lang.String)。然後,CacheRequestBody 將其放置在可從 ServerWebExchange.getAttributes() 取得的屬性中,金鑰定義於 ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR

此篩選器僅適用於 HTTP (包括 HTTPS) 請求。