How to implement a replay mechanism in jersey-client java

I am making several HTTP avi calls using jersey-client. Now I want to retry to request a failure. Let's say if the return error code is not 200, I want to repeat it again several times. How To Do It Using A Jersey Client

+4
source share
2 answers

To implement attempts in any situation, check 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 repeats if the response status is! = 200, up to 3 times, with a delay of 1 second between attempts.

+4
source

It's late for the party here, but there are a few different mechanisms you can use. The synchronous method will 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;
}

backoff Googles: https://developers.google.com/api-client-library/java/google-http-java-client/backoff

+1

Source: https://habr.com/ru/post/1599854/


All Articles