我对ReactiveX和反应式编程都很陌生。我需要为Couchbase CAS操作实现一个重试机制,但是Couchbase网站上的示例显示了一个retryWhen,看起来会无限重试。我需要在其中设置重试限制和重试计数。
简单的retry()可以工作,因为它接受一个retryLimit,但我不想让它在每个异常发生时都重试,只想在出现CASMismatchException时重试。
有什么建议吗?我正在使用RxJava库。
.retryWhen(notification ->
notification
.zipWith(Observable.range(1, 5), Tuple::create)
.flatMap(att ->
att.value2() == 3 ? Observable.error(att.value1()) : Observable.timer(att.value2(), TimeUnit.SECONDS)
)
)
你的使用情境与 RxJava 文档 这里 中的情境非常接近。
重新启动这个线程,因为在Couchbase Java SDK 2.1.2中有一种新的更简单的方法来实现这个功能:使用RetryBuilder
:
Observable<Something> retryingObservable =
sourceObservable.retryWhen(
RetryBuilder
//will limit to the relevant exception
.anyOf(CASMismatchException.class)
//will retry only 5 times
.max(5)
//delay doubling each time, from 100ms to 2s
.delay(Delay.linear(TimeUnit.MILLISECONDS, 2000, 100, 2.0))
.build()
);