webFlux获取不到body体解决办法

/**
 * 缓存body内容.
 *
 * @return
 */
public Mono readBody(ServerWebExchange exchange,
                           GatewayFilterChain chain,
                           GatewayContext gatewayContext) {
    log.info("readJsonBody start");
    // 解析exchange,返回一个全新的mono(缓存body的mono)
    Mono monoData = DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
        // 创建一个容量为dataBuffer容量大小的字节数组
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        // dataBuffer类容读取到bytes中
        dataBuffer.read(bytes);
        // 释放缓冲区
        DataBufferUtils.release(dataBuffer);
        // 创建新缓冲区并写入数据
        Flux cachedFlux = Flux.defer(() -> {
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            DataBufferUtils.retain(buffer);
            return Mono.just(buffer);
        });
        // 由于原来的request请求参数被消费,需要提供新的请求
        ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public Flux getBody() {
                return cachedFlux;
            }
        };
        // 创建新的exchange并构建解析的数据
        ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
        Mono mono = ServerRequest.create(mutatedExchange, MESSAGE_READERS)
            .bodyToMono(String.class)
            .doOnNext(objectValue -> {
                log.info("resolve success postBody is:{}", objectValue);
                gatewayContext.setCacheBody(objectValue);
            }).then(chain.filter(mutatedExchange));
        return mono;
    });
    return monoData;
}

你可能感兴趣的:(springboot)