Repeat java request RestTemplate of HTTP request if host is disconnected

Hi, I am using spring RestTemplate to call the REST API. The API can be very slow or even standalone. My application creates a cache by sending thousands of requests one after another. Answers can be very slow because they contain a lot of data.

I have already increased the wait time to 120 seconds. My problem now is that the API can be offline, and I get an org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool exception.

In case the API is disabled, the application should wait and try again until the API is connected again.

Can I achieve this in a RestTemplate out of the box without creating exception loops?

Thanks!

+5
source share
2 answers

Use the Spring Snooze Project ( https://dzone.com/articles/spring-retry-ways-integrate , https://github.com/spring-projects/spring-retry ).

It is designed to solve problems like yours.

+5
source

I had the same situation and I found a solution to solve the problem. Give an answer in the hope that this will help someone else. You can set the maximum number of attempts and the time interval for each attempt.

 @Bean public RetryTemplate retryTemplate() { int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt")); int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval")); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(maxAttempt); FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy(); backOffPolicy.setBackOffPeriod(retryTimeInterval); // 1.5 seconds RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(retryPolicy); template.setBackOffPolicy(backOffPolicy); return template; } 

And my rest service, which I want to perform, is below.

 retryTemplate.execute(context -> { System.out.println("inside retry method"); ResponseEntity<?> requestData = RestTemplateProvider.getInstance().postAsNewRequest(bundle, ServiceResponse.class, serivceURL, CommonUtils.getHeader("APP_Name")); _LOGGER.info("Response ..."+ requestData); throw new IllegalStateException("Something went wrong"); }); 
+1
source

All Articles