我正在使用jersey-client进行一些http rest api调用。现在,我想对失败的请求进行重试。假设返回的错误代码不是200,那么我想重试几次。如何使用Jersey客户端完成此操作
发布于 2015-08-01 00:31:31
要在任何情况下实现重试,请查看Failsafe
RetryPolicy retryPolicy = new RetryPolicy()
.retryIf((ClientResponse response) -> response.getStatus() != 200)
.withDelay(1, TimeUnit.SECONDS)
.withMaxRetries(3);
Failsafe.with(retryPolicy).get(() -> webResource.post(ClientResponse.class, input));此示例在响应状态!= 200时重试,最多3次,两次重试之间的延迟为1秒。
发布于 2016-01-15 10:46:32
晚到这里,但有几种不同的机制你可以使用。同步方法看起来像这样:
public Response execWithBackoff(Callable<Response> i) {
ExponentialBackOff backoff = new ExponentialBackOff.Builder().build();
long delay = 0;
Response response;
do {
try {
Thread.sleep(delay);
response = i.call();
if (response.getStatusInfo().getFamily() == Family.SERVER_ERROR) {
log.warn("Server error {} when accessing path {}. Delaying {}ms", response.getStatus(), response.getLocation().toASCIIString(), delay);
}
delay = backoff.nextBackOffMillis();
} catch (Exception e) { //callable throws exception
throw new RuntimeException("Client request failed", e);
}
} while (delay != ExponentialBackOff.STOP && response.getStatusInfo().getFamily() == Family.SERVER_ERROR);
if (response.getStatusInfo().getFamily() == Family.SERVER_ERROR) {
throw new IllegalStateException("Client request failed for " + response.getLocation().toASCIIString());
}
return response;
}指数回退实现基于Google客户端库:https://developers.google.com/api-client-library/java/google-http-java-client/backoff
https://stackoverflow.com/questions/31651236
复制相似问题