我将Failsafehttps://github.com/jhalterman/failsafe)用作重试逻辑框架,并想了解更多有关故障保险的“运行”方法如何工作的信息。

假设我有:

void MyCurrentFunction(parameter) {
    Failsafe.with(MY_RETRY_POLICY)
            .run(() -> runJob(parameter));
    OtherFunction1();
}


然后,当MyCurrentFunction运行时,Failsafe.run会阻止MyCurrentFunction的执行吗?换句话说,OtherFunction1将在所有重试完成之前执行吗?

最佳答案

这是检查您的问题的代码(注意:该代码与Failsafe 2.0相关)

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .withMaxRetries(3);

private void myCurrentFunction() {
    Failsafe.with(MY_RETRY_POLICY)
            .run(() -> runJob());

    otherFunction1();
}

private void otherFunction1() {
    System.out.println("OtherFunction1");
}

private void runJob() {
    System.out.println("run job...");

    throw new RuntimeException("Exception");
}


答案是不;在所有重试完成之前,不会执行OtherFunction1
实际上,如果所有重试均失败,则将不会调用OtherFunction1

这是测试代码的输出

run job...
run job...
run job...
run job...

java.lang.RuntimeException: Exception


不过,您可以修改重试策略以执行OtherFunction1
1)每次重试后

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .onRetry(fail -> otherFunction1())
        .withMaxRetries(3);


2)重试失败后

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .onFailure(fail -> otherFunction1())
        .withMaxRetries(3);

08-06 21:27