gpt4 book ai didi

java - Guava 重试器调用函数直到发生异常

转载 作者:行者123 更新时间:2023-12-02 10:23:04 27 4
gpt4 key购买 nike

假设我有一些这样的代码:

public void deleteResource(UUID resourceId) {
deleteFromDb();
deleteFromALotOfOtherPlaces(); // Takes a long time!
}

public DescribeResourceResult describeResource(UUID resourceId) throws ResourceNotFoundException {
return getResourceDescription(resourceId);
}

不幸的是,删除并没有表明它已完成。验证删除是否已完成的唯一方法是调用describeResource,如果资源已被删除,它将引发异常。

我想编写一个重试器,它将重复调用describeResrouce,直到发生ResourceNotFoundException。我怎样才能做到这一点?

这是我到目前为止所拥有的:

final Retryer<ResourceNotFoundException> deleteResourceRetryer = RetryerBuilder.<ResourceNotFoundException>newBuilder()
.withWaitStrategy(WaitStrategies.fixedWait(500, TimeUnit.MILLISECONDS))
.withStopStrategy(StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))
.build();

// Error: Bad return type in lambda expression: DescribeResourceResult cannot be converted to ResourceNotFoundException
deleteResourceRetryer.call(() -> describeResource(resourceId));

谢谢!

最佳答案

我对 Guava 的 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();

最后,开始重试

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
}

希望对你有帮助!

关于java - Guava 重试器调用函数直到发生异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com