1

有没有办法重试成功的请求?所有示例都指向当 RestTempalte 发生故障时的重试行为。我想发送一个请求,等待响应并检查响应中的一个字段,如果它不是预期的状态,则重试请求。这可以使用 RestTemplate 来完成吗?我唯一知道的是做一个线程睡眠并再次调用该方法。我想避免这种情况。

4

1 回答 1

0

试试看 Spring-Retry 能不能帮到你:

http://www.mastertheboss.com/jboss-frameworks/spring/using-spring-retry-to-consume-rest-services

如果您指定哪些响应是可接受的,它将重试您的方法:

下面的示例代码:

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=10,value=RuntimeException.class,backoff = @Backoff(delay = 10000,multiplier=2))
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;
}
于 2020-11-20T18:24:13.047 回答