Springboot webFlux filter 获取 requestBody
public Mono<ServerHttpRequest> generateNewRequest(ServerHttpRequest request) { return DataBufferUtils.join(request.getBody()) .map(dataBuffer -> { byte[] bytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(bytes);
//释放内存 DataBufferUtils.release(dataBuffer); return bytes; }).flatMap(bodyBytes -> { log.info("request body :{}", new String(bodyBytes)); return Mono.just(generateNewRequest(request, bodyBytes)); }); } public ServerHttpRequest generateNewRequest(ServerHttpRequest request, byte[] bytes) { DataBuffer dataBuffer = stringBuffer(bytes); Flux<DataBuffer> flux = Flux.just(dataBuffer); ServerHttpRequest newRequest = new ServerHttpRequestDecorator(request) { @Override public Flux<DataBuffer> getBody() { return flux; } @Override public HttpHeaders getHeaders() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.remove(HttpHeaders.CONTENT_LENGTH); httpHeaders.putAll(request.getHeaders()); if (bytes.length > 0L) { httpHeaders.setContentLength(bytes.length); } else { httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked"); } return httpHeaders; } }; return newRequest; }
private DataBuffer stringBuffer(byte[] bytes) {
NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
buffer.write(bytes);
return buffer;
}