Retries in the Java WS Client

Hi all!

I’m using the Sonar WS Client for Java (org.sonarsource.sonarqube.sonar-ws), version 9.9.0.65466.

Is there a built-in way to retry requests to the Sonarqube server using this library (if a timeout occurs because of network instability, for example)? Or do I need to implement it myself?

Thanks!

Hi,

Welcome to the community!

You’ll need to implement it yourself.

 
HTH,
Ann

Here’s my solution in case it helps anyone in the future:

  1. Add dependency dev.failsafe.failsafe-okhttp in your pom.xml / build.gradle
  2. Create class org.sonarqube.ws.client.HttpConnectorWithRetries in your project (the class NEEDS to be in the org.sonarqube.ws.client package)
  3. Copy the code from the original org.sonarqube.ws.client.HttpConnector from sonar-ws
  4. Add the following static attribute (tweak it to your needs):
private static final RetryPolicy<Response> retryPolicy = RetryPolicy.<Response>builder()
        .handle(IOException.class)
        .onRetry(event -> LOGGER.info("Retrying request for the {} time", event.getAttemptCount()))
        .withBackoff(Duration.ofSeconds(1), Duration.ofSeconds(16))
        .withMaxAttempts(5)
        .build();
  1. Update the doCall method to use the previously created retryPolicy:
private static Response doCall(OkHttpClient client, Request okRequest) {
    Call call = client.newCall(okRequest);
    FailsafeCall failsafeCall = FailsafeCall.with(retryPolicy).compose(call);
    try {
        return failsafeCall.execute();
    } catch (IOException e) {
        throw new IllegalStateException("Fail to request url: " + okRequest.url(), e);
    }
}
  1. When you initialize your WsClient, make sure to use the custom HttpConnectorWithRetries:
WsClient sonarWsClient = WsClientFactories.getDefault().newClient(HttpConnectorWithRetries.newBuilder().url("sonarUrl").token("sonarToken").build());
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.