根据响应重试 WebClient

我创建了一个 Spring webflux webclient。我想根据我的响应重复相同的操作。例如:如果数据仍然为空,我想重试获取数据。怎么做 ?


Flux<Data> data = webClient.get()

                .uri("/api/users?page=" + page)

                .retrieve()

                .flatMap(o -> {

                  o.subscribe(data -> {

                      if(data == null) {

                         // WHAT TO DO HERE, TO REPEAT THE SAME CALL ?

                         o.retry();

                      }

                });

                return o;

            })

            .bodyToFlux(Data.class);


饮歌长啸
浏览 117回答 1
1回答

慕森王

您可以使用retry(Predicate<? super Throwable> retryMatcher),它将根据可抛出条件重试该操作。在下面的代码中,如果从客户端接收到的数据为空,我将返回 Mono.error,然后根据重试中的错误条件再次执行上述操作。您还可以限制重试次数,retry(long numRetries, Predicate<? super Throwable> retryMatcher)final Flux<Data> flux = WebClient.create().get().uri("uri").exchange().flatMap(data -> {&nbsp; &nbsp; &nbsp; if (data == null)&nbsp; &nbsp; &nbsp; &nbsp; return Mono.error(new RuntimeException());&nbsp; &nbsp; &nbsp; return Mono.just(data);&nbsp; &nbsp; }).retry(throwable -> throwable instanceof RuntimeException)&nbsp; &nbsp; &nbsp; &nbsp; .flatMap(response -> response.bodyToMono(Data.class)).flux();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java