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)请求。 |