Java 在异常发生之前调用函数的Guava retryer
假设我有如下代码:Java 在异常发生之前调用函数的Guava retryer,java,guava,Java,Guava,假设我有如下代码: public void deleteResource(UUID-resourceId){ deleteFromDb(); DeleteFromAlotOtherPlaces();//需要很长时间! } 公共描述符源结果描述符源(UUID resourceId)引发ResourceNotFoundException{ 返回getResourceDescription(resourceId); } 不幸的是,删除并不表示它已完成。验证删除是否已完成的唯一方法是调用descrip
public void deleteResource(UUID-resourceId){
deleteFromDb();
DeleteFromAlotOtherPlaces();//需要很长时间!
}
公共描述符源结果描述符源(UUID resourceId)引发ResourceNotFoundException{
返回getResourceDescription(resourceId);
}
不幸的是,删除并不表示它已完成。验证删除是否已完成的唯一方法是调用descripberesource
,如果资源已被删除,它将引发异常
我想编写一个retryer,它将反复调用descripberesrouce
,直到发生ResourceNotFoundException
为止。我该怎么做
以下是我目前掌握的情况:
final Retryer deleteResourceRetryer=RetryerBuilder.newBuilder()
.withWaitStrategy(waitStrategys.fixedWait(500,时间单位.毫秒))
.使用停止策略(停止策略。停止后延迟(10,时间单位。秒))
.build();
//错误:lambda表达式中的返回类型错误:无法将DescribeSourceResult转换为ResourceNotFoundException
deleteResourceRetryer.call(()->DescriberSource(resourceId));
谢谢大家! 我不太熟悉番石榴的
Retryer
,因此经过短暂的调查,我无法找到现成的StopStrategy
,因此我的建议是自己实施
static class OnResourceNotFoundExceptionStopStrategy implements StopStrategy {
@Override
public boolean shouldStop(Attempt attempt) {
if (attempt.hasException()
&& attempt.getExceptionCause() instanceof ResourceNotFoundException) {
return true;
}
return false;
}
}
使用该策略,当您捕获ResourceNotFoundException
时,重试将停止。之后,修复类型并正确定义Retryer
final Retryer<DescribeResourceResult> deleteResourceRetryer = RetryerBuilder
.<DescribeResourceResult>newBuilder()
.retryIfResult(Predicates.notNull())
.withWaitStrategy(WaitStrategies.fixedWait(500, TimeUnit.MILLISECONDS))
.withStopStrategy(new OnResourceNotFoundExceptionStopStrategy())
.build();
希望有帮助 使用:
RetryPolicy RetryPolicy=new RetryPolicy()
.abortOn(ResourceNotFoundException.class);
.有延迟(持续时间500百万)
.最大持续时间(持续时间为秒(10));
Failsafe.with(retryPolicy).get(()->getResourceDescription(resourceId));
try {
deleteResourceRetryer.call(() -> describeResource(resourceId));
} catch (ExecutionException e) {
// should not happens, because you will retry if any exception rather
// than ResourceNotFoundException raised in your describeResource method
} catch (RetryException e) {
// should not happens, because my implementation of StopStrategy
// (as it looks in this example) is effectively infinite, until target exception.
// For sure you're free to override it to anything you want
}
RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
.abortOn(ResourceNotFoundException.class);
.withDelay(Duration.ofMillis(500))
.withMaxDuration(Duration.ofSeconds(10));
Failsafe.with(retryPolicy).get(() -> getResourceDescription(resourceId));