1 回答

TA貢獻1884條經(jīng)驗 獲得超4個贊
對的,這是可能的。
Mono
有兩個重新訂閱的概念(因此,重新觸發(fā)請求)
retry = 如果上游完成異常,則重新訂閱
如果上游成功完成, repeat = 重新訂閱
每個概念都有Mono
針對不同用例的多個重載方法。尋找retry*
和repeat*
方法。例如,要無延遲地重試最大次數(shù),請使用retry(int numRetries)
.
retryWhen
通過和方法支持更復雜的用例repeatWhen
,如以下示例所示。
重試時
如果單聲道以異常完成最多 5 次,每次嘗試之間間隔 5 秒,則重試:
// From reactor-core >= v3.3.4.RELEASE import reactor.util.retry.Retry;this.webClient .post() .uri(SERVICE_URL) .body(BodyInserters.fromValue(docRequest)) .retrieve() .bodyToMono(Document.class) .retryWhen(Retry.fixedDelay(5, Duration.ofSeconds(5))) .delaySubscription(Duration.ofSeconds(10))
重試構(gòu)建器支持其他退避策略(例如指數(shù))和其他選項以完全自定義重試。
請注意,retryWhen(Retry)
上面使用的方法是在 reactor-core v3.3.4.RELEASE 中添加的,并且該retryWhen(Function)
方法已被棄用。在 reactor-core v3.3.4.RELEASE 之前,您可以使用reactor-extras項目中的重試函數(shù)構(gòu)建器來創(chuàng)建一個Function
傳遞給retryWhen(Function)
.
重復時
如果您需要在成功時重復,請使用.repeatWhen
or.repeatWhenEmpty
而不是.retryWhen
上面的。
使用reactor-extras項目中的repeat 函數(shù)構(gòu)建器來創(chuàng)建repeat Function
,如下所示:
// From reactor-extras
import reactor.retry.Repeat;
this.webClient
.post()
.uri(SERVICE_URL)
.body(BodyInserters.fromValue(docRequest))
.retrieve()
.bodyToMono(Document.class)
.filter(document -> !document.isEmpty())
.repeatWhenEmpty(Repeat.onlyIf(repeatContext -> true)
.exponentialBackoff(Duration.ofSeconds(5), Duration.ofSeconds(10))
.timeout(Duration.ofSeconds(30)))
.delaySubscription(Duration.ofSeconds(10))
如果您想在成功或失敗時重新訂閱,也可以將 a.retry*與 a鏈接。.repeat*
添加回答
舉報