我創建了一個 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);
1 回答

慕森王
TA貢獻1777條經驗 獲得超3個贊
您可以使用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();
添加回答
舉報
0/150
提交
取消