【问题标题】:How to call another api on error Spring WebFlux如何在错误 Spring WebFlux 上调用另一个 api
【发布时间】:2020-11-12 03:19:09
【问题描述】:

我学习WebFlux不是太多,但是我发现了一个我无法解决的任务。如果我当前的请求中出现超时错误,我应该调用另一个 API,并且如果这个 API 返回正常 - 我应该离开这个方法并继续执行我的应用程序。我写了一些代码,但我没有找到解决方案。

        return WebClient.create(documentLocalUrlSettings.getBase())
        .post()
        .uri(documentLocalUrlSettings.getSend())
        .body(BodyInserters.fromValue(sendRequestDto))
        .headers(httpHeadersConsumer)
        .retrieve()
        .bodyToMono(SendAndStatusResponseDto.class)
        .timeout(Duration.ofMillis(10000))
        .retryWhen(errorCurrentAttempt -> errorCurrentAttempt
            .flatMap(tp -> {

                var status = WebClient.create("baseUrl")
                    .post()
                    .uri("callableServiceUrl")
                    .body(BodyInserters.fromValue(StatusRequestDto.class))
                    .retrieve();

                if (status != null && status.getResult().getResultCode() == 10001) {
                    return; 
                } else {
                    return Mono.<Object>error(new InternalRuntimeException(InternalExceptionCode.EX1001));  
                }
            })).block();

UPD:api 调用 - 同步

【问题讨论】:

    标签: java spring spring-boot rest spring-webflux


    【解决方案1】:

    您应该阅读retryWhen() 操作员文档,因为它没有达到您的预期。而不是使用retryWhen(),您应该使用运算符doOnError(),它采用带有从MonoFlux 操作发出的错误参数的函数,并返回新的MonoFlux 发出新行为的值。

    你应该这样做:

    .timeout(Duration.ofMillis(10000))
    .doOnError(error ->
        (error instanceof TimeoutException) 
            ? (/** call API here returning Mono **/) 
            : Mono.error(error)
    ).continueProcessingHere()
    

    还要注意.block() 方法不适合在使用 Webflux 时调用。您正在使用的Webclient 已经是响应式的,因此您不需要阻止结果,而是使用您从中获得的MonoFlux 并使用map()flatMap()onError() 处理结果代码等等运营商的。

    【讨论】:

    • doOnError 接受消费者而不是函数。返回 void 的含义
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多