介绍一下框架版本
spring-boot:2.2.1.RELEASE
spring-cloud:Hoxton.RELEASE(2.2.0.RELEASE)
spring-cloud-gateway:2.2.0.RELEASE
在网上找了很多版本的代码,不起作用,要么获取不到body数据,要么重新封装request到后端服务后,报文丢失或者最大1024b数据,而且代码繁琐。
后面在博客园里一位大佬提供的解决方案
@Component
public class CacheBodyGlobalFilter implements Ordered, GlobalFilter {
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (exchange.getRequest().getHeaders().getContentType() == null) {
return chain.filter(exchange);
} else {
return DataBufferUtils.join(exchange.getRequest().getBody())
.flatMap(dataBuffer -> {
DataBufferUtils.retain(dataBuffer);
Flux cachedFlux = Flux
.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(
exchange.getRequest()) {
@Override
public Flux getBody() {
return cachedFlux;
}
};
return chain.filter(exchange.mutate().request(mutatedRequest).build());
});
}