在使用Spring Cloud Gateway的过程中,经常需要获取request body,比如用来做日志记录、签名验证、加密解密等等。
网上的资料,解决方案五花八门。所以就整理了经过验证且已经在线上使用的两种方法,都是基于官方源码进行扩展。
本文使用的Spring Cloud Gateway版本为2.1.1.RELEASE。
ModifyRequestBodyGatewayFilterFactory
ModifyRequestBodyGatewayFilterFactory
在官方文档中的介绍如下:
This filter can be used to modify the request body before it is sent downstream by the Gateway.
也就是用来修改request body的,既然能修改,自然就能获取到。
java配置
一个简单的配置如下:
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("rewrite_request_body", r -> r.path("/post_json")
.filters(f -> f.modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE, (exchange, s) -> Mono.just(s)))
.uri("l