Spring WebClient - 如何记录成功和失败的响应?

3
我正在尝试使用WebClient创建一个REST调用。
statusWebClient.post()
                .uri(url)
                .bodyValue(createBody(state, number))
                .retrieve()
                .bodyToFlux(String.class)
                .doOnEach(response -> log.debug("Notification was sent to {}, response {}", url, response.get()))
                .doOnError(exception -> log.warn("Failed to send notification to {}, cause {}", url, exception.getMessage()))
                .subscribe();

我只想记录通话结果。成功时,记录带有响应主体的成功消息;在出现5XX错误、超时或其他错误时,记录错误消息。日志应在后台创建(不由创建呼叫的线程创建)。 但是doOnEach每次执行,doOnError正常工作,但也有其他问题。
reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.web.reactive.function.client.WebClientResponseException$InternalServerError: 500 Internal Server Error from POST

记录在日志文件中。

我在一些教程中也看到了onSuccess方法,但在我的设置中没有这样的方法。

如何记录成功和失败消息?


当登录成功或失败时,您可以在.doOnComplete()方法中记录。 - Gurkan İlleez
@Gurkanİlleez .doOnComplete()需要一个Runnable作为参数-没有办法获得响应。 - Mateusz
2个回答

2

你可以为WebClient设置自定义过滤器。

WebClient.builder()
    .filter(logRequest())
    .filter(logResponse());


private ExchangeFilterFunction logRequest() {
    return (clientRequest, next) -> {
        log.debug("Request: {} {}", clientRequest.method(), clientRequest.url());
        return next.exchange(clientRequest);
    };
}

private ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
        log.debug("Response Status: {}", clientResponse.statusCode());
        return Mono.just(clientResponse);
    });
}

2
你的回答不符合要求:“成功时 - 记录带有响应体的成功消息”。 - michaldo

1

这是我创建的东西。看起来工作得很好。

statusWebClient.post()
                .uri(url)
                .bodyValue(createTerminalStatusBody(state, msisdn))
                .retrieve()
                .bodyToMono(String.class)
                .subscribeOn(Schedulers.boundedElastic())
                .doOnSuccess(response -> log.debug("Notification was sent to {}, response {}", url, response))
                .doOnError(exception -> log.warn("Failed to send notification to {}, cause {}", url, exception.getMessage()))
                .onErrorResume(throwable -> Mono.empty())
                .subscribe();

doOnSuccess() 似乎不存在。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接