【问题标题】:mechanism of "run" method of failsafe故障安全“运行”方法的机制
【发布时间】:2019-10-20 16:08:38
【问题描述】:

我正在使用Failsafe (https://github.com/jhalterman/failsafe) 作为我的重试逻辑框架,并想了解更多关于故障安全“运行”方法的工作原理。

假设我有:

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

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

【问题讨论】:

  • 我认为代码是同步的,但您可以很容易地自己测试。

标签: java exception retry-logic java-failsafe


【解决方案1】:

这是检查您的问题的代码(注意:该代码与 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);

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多