Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a re-try logic in RestAssured for a failed REST call

I am using RestAssured for firing API calls and wanted to implement a retry logic if the REST calls fails.

The requirement is because we are getting intermittent 500 response codes for certain APIs which usually work upon a re-try.

I have implemented the following code but it does not seem to work -

HttpClientConfig.HttpClientFactory htc = new HttpClientConfig.HttpClientFactory() {

    @Override
    public HttpClient createHttpClient() {
        DefaultHttpClient d = new DefaultHttpClient();

        d.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(restRetryCount, true));
        return d;
    }
};

RestAssuredConfig rac = RestAssured.config().httpClient(HttpClientConfig.httpClientConfig().httpClientFactory(htc));

Moreover, since RestAssured does not cater the HTTPClient level logging, I tried enabling the logging for the apache httpclient using the java.util.logging but that also does not seem to be working either.

Created a custom.logging.properties file with -

# Enables the header wire and context logging
org.apache.http.level = FINEST
org.apache.http.wire.level = SEVERE

# Enables the context logging for connection management & request execution
org.apache.http.impl.conn.level = FINEST
org.apache.http.impl.client.level = FINEST
org.apache.http.client.level = FINEST

and wrote the following for initiating the logging -

public static Logger initiateHttpTrafficLogging(){
     Logger log = Logger.getLogger("httptraffic.log");
     ClassLoader loader = Thread.currentThread().getContextClassLoader();
     InputStream is = loader.getResourceAsStream("custom.logging.properties");
     try{
         LogManager.getLogManager().readConfiguration(is);
         log.setLevel(Level.FINEST);
         log.addHandler(new ConsoleHandler());
         log.setUseParentHandlers(false);
         log.info("Initiating HTTP Traffic logging ::\n\n");
     } catch (IOException ie){
         Assert.fail("ERROR: Could not load the loggin properties !!!", ie.fillInStackTrace());
    }
    return log;
 }

Could anyone please provide me some direction as to where I am going wrong or any pointers to resolve this issue.

Appreciate your responses. Thanks.

like image 360
palkarrohan Avatar asked Mar 02 '17 06:03

palkarrohan


1 Answers

There is a Spring-retry jar u can integrate that with your application.And you can use something like this in your method

  @Retryable(maxAttempts = 4, backoff = @Backoff(delay = 200),
            include = {RetryableException.class})
    ResponseEntity<String> request(
            String url, HttpMethod method, HttpEntity<?> entity, Class<?> type,
            Map<String, String> parameters
    ) throws Exception{} 

and u need to do @EnableAspectJAutoProxy and @EnableRetry in your configuration class

like image 53
Karthik Bharadwaj Avatar answered Oct 07 '22 01:10

Karthik Bharadwaj