webFlux获取不到body体解决办法

/**
 * 缓存body内容.
 *
 * @return
 */
public Mono<Void> readBody(ServerWebExchange exchange,
                           GatewayFilterChain chain,
                           GatewayContext gatewayContext) {
    log.info("readJsonBody start");
    // 解析exchange,返回一个全新的mono(缓存body的mono)
    Mono<Void> monoData = DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
        // 创建一个容量为dataBuffer容量大小的字节数组
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        // dataBuffer类容读取到bytes中
        dataBuffer.read(bytes);
        // 释放缓冲区
        DataBufferUtils.release(dataBuffer);
        // 创建新缓冲区并写入数据
        Flux<DataBuffer> 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<DataBuffer> getBody() {
                return cachedFlux;
            }
        };
        // 创建新的exchange并构建解析的数据
        ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
        Mono<Void> 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;
}
发布了31 篇原创文章 · 获赞 15 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 像素格子 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览