簡體   English   中英

如何在Spring-retry(Spring Boot)中配置延遲時間

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

是否可以配置@Retryable 這個方法(getCurrentRate)將被調用3次。 首先是5分鍾,然后是10分鍾,最后是15分鍾。 我該如何配置?

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

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

}

您可以使用此配置實現此目的:

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

調用次數:

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

@Sivakumar Neelam Veera

您可以使用RetryTemplate類表示重試邏輯。 在那里,您可以注入依賴項並以編程方式使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM