CacheRequestBody GatewayFilter 工廠
某些情況下需要讀取請求體。由於請求只能讀取一次,我們需要快取請求體。您可以使用 CacheRequestBody 過濾器在將請求傳送到下游之前快取請求體,並從 exchange 屬性中獲取請求體。
以下列表展示瞭如何快取請求體 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 提取請求體並將其轉換為一個體類(例如,前述示例中定義的 java.lang.String)。然後,CacheRequestBody 將其放置在 ServerWebExchange.getAttributes() 可用的屬性中,鍵由 ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR 定義。
| 此過濾器僅適用於 HTTP(包括 HTTPS)請求。 |