seaswalker / posts

0 stars 0 forks source link

Spring retry无限重试和退出策略 #44

Open seaswalker opened 3 years ago

seaswalker commented 3 years ago

RetryTemplate定义:

RetryTemplate retryTemplate = RetryTemplate.builder()
    .infiniteRetry()
    .retryOn(RetryException.class)
    .fixedBackoff(1000)
    .build();

String result = retryTemplate.execute(context -> {
    int code = Service.queryData();
    if (code != Constants.SUCCESS_RESPONSE_CODE) {
        // 这里出错将无限重试
        throw new RetryException();
    }
    return "success";
});

意思是只对RetryException进行无限次重试。 所以退出策略就有两种:

  1. 抛出其它的异常,比如对一个自定义的变量进行检测,抛出其它异常就可以退出无限重试。
  2. 将线程中断,因为当失败进行睡眠等待时必定会被中断打断,此时会抛出BackOffInterruptedException.

另外RetryContext是可以自定义属性的,这样可以在重试之间传递变量。