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

ѕтƒ*_*ѕтƒ 6 java jersey-client jersey-2.0

我正在使用jersey-client做一些http rest api调用.现在我想重试失败请求.如果返回错误代码不是200,那么我想再次重试几次.如何使用Jersey客户端做到这一点

Jon*_*han 6

要在任何情况下执行重试,请查看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));
Run Code Online (Sandbox Code Playgroud)

如果响应状态!= 200,最多3次,重试之间延迟1秒,此示例将重试.


Zac*_*ack 3

虽然已经晚了,但您可以使用几种不同的机制。同步方法看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

指数退避实现基于 Google 客户端库:https://developers.google.com/api-client-library/java/google-http-java-client/backoff