简体   繁体   English

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

[英]How to configure delay time in Spring-retry (Spring Boot)

Is it possible to configure the @Retryable ? 是否可以配置@Retryable This methods (getCurrentRate) will be invoked 3 times. 这个方法(getCurrentRate)将被调用3次。 At first is 5 min, after that 10 min, lastly 15 min. 首先是5分钟,然后是10分钟,最后是15分钟。 How can I configure that ? 我该如何配置?

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

Example

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;
    }

}

You can achieve that with this configuration: 您可以使用此配置实现此目的:

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

Invocations: 调用次数:

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

@Sivakumar Neelam Veera @Sivakumar Neelam Veera

You can express the retry logic using the RetryTemplate class. 您可以使用RetryTemplate类表示重试逻辑。 There you can inject your dependencies and use them programatically. 在那里,您可以注入依赖项并以编程方式使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM