本文介紹了Java Web Flux:如何從ServerHttpResponse獲取正文?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我已實(shí)現(xiàn)自定義ServerHttpRequestDecorator來(lái)獲取請(qǐng)求正文,但無(wú)法對(duì)響應(yīng)執(zhí)行相同的操作。
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain)
{
long start = System.currentTimeMillis();
LogServerWebExchangeDecorator exchangeDecorator = new LogServerWebExchangeDecorator(
exchange);
exchangeDecorator.getResponse().beforeCommit(() ->
{
logRequest(exchangeDecorator.getRequest(), exchangeDecorator.getRequestBody());
logResponse(exchangeDecorator.getRequest(), exchangeDecorator.getResponse(), start);
return Mono.empty();
});
return chain.filter(exchangeDecorator);
}
如何實(shí)現(xiàn)同樣的目標(biāo)?
推薦答案
private class LogServerHttpResponseDecorator extends ServerHttpResponseDecorator
{
private final FastByteArrayOutputStream fastByteArrayOutputStream;
public LogServerHttpResponseDecorator(ServerHttpResponse response, LoggingContext loggingContext)
{
super(response);
fastByteArrayOutputStream = new FastByteArrayOutputStream();
response.beforeCommit(LoggingContextUtils.withContext(loggingContext, (Supplier<Mono<Void>>) () ->
{
logResponse(byteArrayToString(fastByteArrayOutputStream.toByteArray(),
getHeaders()));
return Mono.empty();
}));
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body)
{
return super.writeWith(Flux.from(body).map(buffer ->
{
readBuffer(fastByteArrayOutputStream, buffer);
return buffer;
}));
}
@Override
public Mono<Void> writeAndFlushWith(
Publisher<? extends Publisher<? extends DataBuffer>> body)
{
return super.writeAndFlushWith(Flux.from(body).map(publisher ->
Flux.from(publisher).map(buffer ->
{
readBuffer(fastByteArrayOutputStream, buffer);
return buffer;
})));
}
}
private void readBuffer(FastByteArrayOutputStream fastByteArrayOutputStream, DataBuffer buffer)
{
try
{
Channels.newChannel(fastByteArrayOutputStream)
.write(buffer.asByteBuffer().asReadOnlyBuffer());
}
catch (IOException e)
{
if (LoggingUtils.isLoggable(LOGGER, Level.ERROR))
{
LoggingUtils.log(LOGGER, Level.ERROR, null, "Unable to log", e);
}
}
}
這篇關(guān)于Java Web Flux:如何從ServerHttpResponse獲取正文?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,