本文介绍了根据结果重试方法(而不是异常)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有以下签名的方法:
I have a method with the following signature:
public Optional<String> doSomething() {
...
}
如果我得到一个空的Optional
,我想重试此方法,只有3次后返回空的Optional
.
If I get an empty Optional
I'd like to retry this method and only after 3 times return the empty Optional
.
我已经查看并找到了Retryable
spring批注,但它似乎仅适用于Exceptions.
I've looked and found the Retryable
spring annotation, but it seems to only work on Exceptions.
如果可能,我想为此使用一个库,并避免:
If possible I'd like to use a library for this, and avoid:
- 创建并引发异常.
- 亲自编写逻辑.
推荐答案
我一直在使用故障保护内建重试.您可以根据谓词和异常重试.
I have been using failsafe build in retry.You can retry based on predicates and exceptions.
您的代码如下:
private Optional<String> doSomethingWithRetry() {
RetryPolicy<Optional> retryPolicy = new RetryPolicy<Optional>()
.withMaxAttempts(3)
.handleResultIf(result -> {
System.out.println("predicate");
return !result.isPresent();
});
return Failsafe
.with(retryPolicy)
.onSuccess(response -> System.out.println("ok"))
.onFailure(response -> System.out.println("no ok"))
.get(() -> doSomething());
}
private Optional<String> doSomething() {
return Optional.of("result");
}
如果可选参数不为空,则输出为:
If the optional is not empty the output is:
predicate
ok
否则看起来像:
predicate
predicate
predicate
no ok
这篇关于根据结果重试方法(而不是异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!