如何在Spring-retry(Spring Boot)中配置延迟时间

Joh*_*Joe 7 java rest spring spring-boot

是否可以配置@Retryable?这个方法(getCurrentRate)将被调用3次.首先是5分钟,然后是10分钟,最后是15分钟.我该如何配置?

@Retryable(maxAttempts=3,value=RuntimeException.class,backoff = @Backoff(delay = 1000))
Run Code Online (Sandbox Code Playgroud)

public class RealExchangeRateCalculator implements ExchangeRateCalculator {

    private static final double BASE_EXCHANGE_RATE = 1.09;
    private int attempts = 0;
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

   @Retryable(maxAttempts=3,value=RuntimeException.class,backoff = @Backoff(delay = 1000))
    public Double getCurrentRate() {

        System.out.println("Calculating - Attempt " + attempts + " at " + sdf.format(new Date()));
        attempts++;

        try {
            HttpResponse<JsonNode> response = Unirest.get("http://rate-exchange.herokuapp.com/fetchRate")
                .queryString("from", "EUR")
                .queryString("to","USD")
                .asJson();

            switch (response.getStatus()) {
            case 200:
                return response.getBody().getObject().getDouble("Rate");
            case 503:
                throw new RuntimeException("Server Response: " + response.getStatus());
            default:
                throw new IllegalStateException("Server not ready");
            }
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

    @Recover
    public Double recover(RuntimeException e){
        System.out.println("Recovering - returning safe value");
        return BASE_EXCHANGE_RATE;
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 13

您可以使用此配置实现此目的:

@Retryable(
  maxAttempts=3,
  value=RuntimeException.class,
  backoff = @Backoff(
    delay = 300000,
    multiplier = 2,
    maxDelay = 900000
  )
)
Run Code Online (Sandbox Code Playgroud)

调用次数:

  1. 5m后〜 Delay = 300000
  2. 10m后〜 Delay = 300000 * 2 = 600000
  3. 15m后〜 Delay = 600000 * 2 = 1200000 with Max Delay of 900000

  • 这是不正确的。请注意,“maxAttemps”已经[包括第一次失败](https://docs.spring.io/spring-retry/docs/api/current/org/springframework/retry/annotation/Retryable.html#maxAttempts--) ,因此**最多重试 2 次**。如果需要重试 3 次,请设置 maxAttempts=4。此外,设置“maxDelay”对于限制执行之间的时间是必要的。否则,第三次重试(第四次调用)将在 20 分钟而不是 15 分钟后开始。 (4认同)
  • 你甚至需要设置maxDelay吗?您已经在设置maxAttempts. (2认同)