首页 文章

Spring WebFlux webclient处理ConnectTimeoutException

提问于
浏览
1

我使用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);

onStatus 方法为每个 400 / 500 响应代码返回一个空 Mono . 如何进行连接超时甚至读/写超时 . 就像现在它只是扔了 io.netty.channel.ConnectTimeoutException ,这是 onStatus 没有处理

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

回到 spring-web ,带有 RestTemplate ,我记得连接超时也导致 RestClientException . 所以我们可以 grab 所有异常和超时的 RestClientException . 有没有办法我们可以用 WebClient 做到这一点?

1 回答

  • 1

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

    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);
    

相关问题