2017-08-29 269 views
3

是否可以配置@Retryable?此方法(getCurrentRate)將被調用3次。首先是5分鐘,之後10分鐘,最後15分鐘。我該如何配置?如何在Spring-retry(Spring Boot)中配置延遲時間

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

} 
+1

延遲由退避註釋,退避= @Backoff加入(延遲= 300000,乘法器= 2),該值是在毫秒, 沒有明確的設置,默認值是1000ms的固定延遲 只有延遲()設置:退避是一個固定的延遲與該值 當設置delay()和maxDelay()時,退避均勻分佈在這兩個價值es 使用delay(),maxDelay()和multiplier(),退避指數增長到最大值 –

回答

3

可以實現與這種配置:

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

調用次數:

  1. 後5米〜Delay = 300000
  2. 後10米〜Delay = 300000 * 2 = 600000
  3. 15米後〜Delay = 600000 * 2 = 1200000 with Max Delay of 900000
+0

什麼是最大延遲? –

+0

'maxDelay'是重試之間的最大等待時間,以毫秒爲單位。你的情況應該是90000ms〜15m。使用'delay','maxDelay'和'multiplier',退避指數增長到最大值。 更多的信息在這裏:https://docs.spring.io/spring-retry/docs/api/current/org/springframework/retry/annotation/Backoff.html#maxDelay() –

+0

它停止運行後第二個 –