How to implement a retry mechanism in jersey-client java

眉间皱痕 提交于 2020-12-05 08:45:13

问题


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


回答1:


For implementing retries in any situation, check out 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.




回答2:


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://stackoverflow.com/questions/31651236/how-to-implement-a-retry-mechanism-in-jersey-client-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!