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

时间:2017-08-29 16:07:06

标签: java spring rest 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;
    }

}

2 个答案:

答案 0 :(得分:9)

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

var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

var evens = []; 
var odds = [];  

function oddsAndEvens(nums) {
	for(var i = 0; i < nums.length; i++){
      if(nums[i] % 2 === 0){
        evens.push(nums[i])
      }
      else if (!nums[i] % 2 === 0) {
		odds.push(nums[i])
      }
    }  
      console.log(evens);
      console.log(odds);
    //I need it to "return" the array,
    //not console log
      
}
  
console.log(oddsAndEvens(myNums));

调用次数:

  1. 5m~ @Retryable( maxAttempts=3, value=RuntimeException.class, backoff = @Backoff( delay = 300000, multiplier = 2, maxDelay = 900000 ) )
  2. 之后
  3. 10m后〜Delay = 300000
  4. 15m~ Delay = 300000 * 2 = 600000
  5. 之后

答案 1 :(得分:-1)

@Sivakumar Neelam Veera

您可以使用RetryTemplate类表达重试逻辑。在那里,您可以注入依赖项并以编程方式使用它们。