根据响应重试 WebClient
Retry the WebClient based on the response
我创建了一个 Spring webflux webclient.I 想根据我的回复重复相同的操作。例如:如果数据仍然是空的,我想重试获取数据。怎么做?
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);
您可以使用 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 -> {
if (data == null)
return Mono.error(new RuntimeException());
return Mono.just(data);
}).retry(throwable -> throwable instanceof RuntimeException)
.flatMap(response -> response.bodyToMono(Data.class)).flux();
我创建了一个 Spring webflux webclient.I 想根据我的回复重复相同的操作。例如:如果数据仍然是空的,我想重试获取数据。怎么做?
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);
您可以使用 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 -> {
if (data == null)
return Mono.error(new RuntimeException());
return Mono.just(data);
}).retry(throwable -> throwable instanceof RuntimeException)
.flatMap(response -> response.bodyToMono(Data.class)).flux();