Spring WebFlux webclient 处理 ConnectTimeoutException

Den*_*sen 5 reactor-netty spring-webflux

我正在使用 Spring WebFlux webclient 进行 REST 调用。我已经以3000毫秒为单位配置了连接超时,因此:

WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(options -> options
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)))
    .build();

return webClient.get()
    .uri("http://localhost:8081/resource")
    .retrieve()
    .onStatus(HttpStatus::isError, clientResponse -> {
        // Some logging..
        return Mono.empty();
    })
    .bodyToMono(MyPojo.class);
Run Code Online (Sandbox Code Playgroud)

onStatus方法Mono为每个400/500响应代码返回一个空值。我怎样才能对连接超时甚至读/写超时做同样的事情。现在它只是抛出一个io.netty.channel.ConnectTimeoutException不被处理的onStatus

我的@ExceptionHandler控制器上不需要,因为这些 REST 调用是更复杂流程的一部分,并且通过空Mono元素应该被忽略。

回来spring-web用一个RestTemplate,我记得连接超时也导致了一个RestClientException。所以我们可以捕获RestClientException所有异常和超时。有没有办法我们也可以做到这一点WebClient

Bri*_*zel 5

onError***Reactor为此提供了多个运算符:

return webClient.get()
    .uri("http://localhost:8081/resource")
    .retrieve()
    .onErrorResume(ex -> Mono.empty())
    .onStatus(HttpStatus::isError, clientResponse -> {
        // Some logging..
        return Mono.empty();
    })
    .bodyToMono(MyPojo.class);
Run Code Online (Sandbox Code Playgroud)