【问题标题】:Get the current backoff value when using Spring RetryTemplate使用 Spring RetryTemplate 时获取当前退避值
【发布时间】:2019-12-06 00:13:57
【问题描述】:

所以我一直在尝试使用 Spring 的重试模板。一切都按预期工作。然而,我想要的一件事是能够提取或记录正在使用的当前退避时间。我浏览了文档/到处搜索,但找不到任何简单的方法。

    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();

        exponentialBackOffPolicy.setMaxInterval(10000); // 10 secs
        exponentialBackOffPolicy.setMultiplier(2);    // double the backoff
        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(2);
        retryTemplate.setRetryPolicy(retryPolicy);

        return retryTemplate;
    }

而我就是这样使用的……

retryTemplate.execute(arg0 -> {
    myService.templateRetryService();
    return null;
});

RetryCallback 仅提供 RetryConext 但这不包含我需要的内容。

欢迎任何想法。谢谢。

【问题讨论】:

  • 在你的情况下,如果你想跟踪状态,你不应该像FixedBackOffPolicy那样使用StatelessBackOffPolicy。也许像ExponentialBackOffPolicy 这样的东西会给你控制权。您可以将其子类化并将其分配给 retryTemplate 并在您的自定义类中记录内容。
  • 谢谢,我很抱歉,但 FixedBackOffPolicy 是一个复制/粘贴错误。我现在已经更正了这个问题以反映这一点。我正在使用 ExponentialBackoffPolicy。即使我要对该策略进行子类化,但是我看不到任何访问内部退避时间的方法。我将不得不以某种方式维护和管理我自己的 backOff 时间,这将首先抵消使用 spring 库的好处。

标签: java spring spring-retry retrytemplate


【解决方案1】:

您可以在ExponentialBackOffPolicy上设置自定义Sleeper来记录时间。

/**
 * Public setter for the {@link Sleeper} strategy.
 * @param sleeper the sleeper to set defaults to {@link ThreadWaitSleeper}.
 */
public void setSleeper(Sleeper sleeper) {
    this.sleeper = sleeper;
}

默认的睡眠者是这样的:

@SuppressWarnings("serial")
public class ThreadWaitSleeper implements Sleeper {

    @Override
    public void sleep(long backOffPeriod) throws InterruptedException {
        Thread.sleep(backOffPeriod);
    }

}

【讨论】:

  • 哦,这正是我想要的,应该可以完美运行。谢谢!
猜你喜欢
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 2017-12-20
  • 1970-01-01
  • 2014-03-16
  • 2019-02-02
  • 2020-01-06
相关资源
最近更新 更多