java jersey-client java中如何实现重试机制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31651236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement a retry mechanism in jersey-client java
提问by ?т?
I am doing some http rest api calls using jersey-client. Now I want to do a retry for a failure request. Say if the return error code is not 200 then I want to retry it again for a few times. How can do it using Jersey client
我正在使用 jersey-client 进行一些 http rest api 调用。现在我想对失败请求进行重试。假设返回错误代码不是 200,那么我想重试几次。如何使用 Jersey 客户端执行此操作
回答by Jonathan
For implementing retries in any situation, check out Failsafe:
要在任何情况下实现重试,请查看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));
This example retries if the response status != 200, up to 3 times, with a 1 second delay between retries.
此示例在响应状态 != 200 时重试,最多 3 次,重试之间有 1 秒的延迟。
回答by Zack
Late to the party here, but there are a couple different mechanisms you can use. A synchronous method would look something like this:
在这里聚会迟到了,但您可以使用几种不同的机制。同步方法如下所示:
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;
}
The exponential backoff implementation is based off of Googles client library: https://developers.google.com/api-client-library/java/google-http-java-client/backoff
指数退避实现基于谷歌客户端库:https: //developers.google.com/api-client-library/java/google-http-java-client/backoff