简体   繁体   English

如何在jersey-client java中实现重试机制

[英]How to implement a retry mechanism in jersey-client java

I am doing some http rest api calls using jersey-client. 我正在使用jersey-client做一些http rest api调用。 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. 如果返回错误代码不是200,那么我想再次重试几次。 How can do it using Jersey client 如何使用Jersey客户端做到这一点

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秒,此示例将重试。

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 指数退避实施基于Googles客户端库: https//developers.google.com/api-client-library/java/google-http-java-client/backoff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM