有没有办法重试成功的请求?所有的例子都指向resttempalte上出现故障时的重试行为。我想发送一个请求,等待响应并检查响应中的一个字段,如果请求不是预期状态,请重试。这可以使用rest模板来完成吗?我所知道的唯一一件事就是执行线程休眠并再次调用该方法。我想避免这样。
9fkzdhlc1#
尝试查看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; }
1条答案
按热度按时间9fkzdhlc1#
尝试查看spring retry是否可以帮助您:
http://www.mastertheboss.com/jboss-frameworks/spring/using-spring-retry-to-consume-rest-services
如果您指定哪些响应是可接受的,它将重试您的方法:
示例代码如下: