Consecutive same Rest API Call using Spring Boot

Viewed 55

I want to call a Rest API using springboot till a field in the response (hasMoreEntries) is 'Y'. Currently, am simply using a while loop and checking the response for the flag and calling the API again. PFB pseudocode. Is there any other efficient way to do this OR what is the best way.

String hasMoreEntries="Y";
while(!hasMoreEntries.equals("N"))
{
response = \\PERFORM REST SERVICE CALL HERE
hasMoreEntries=respone.body().getHasMoreEntries();
}
1 Answers

You can use Spring Retry mechanism. For example you can create RetryTemplate bean with custom exception ResponseValidateException that is thrown when the response is invalid:

@Bean
public RetryTemplate retryTemplate() {
    return RetryTemplate.builder()
            .retryOn(ResponseValidateException.class)
            .infiniteRetry()
            .fixedBackoff(2000L)
            .build();
}

And your service:

@Service
public class YourService {
    @Autowired
    private RetryTemplate retryTemplate;

    public void bar() {
        final ResponseEntity<SomeObject> entity = retryTemplate.execute(retryContext -> {
            final ResponseEntity<SomeObject> response = null;
            if ("Y".equals(response.getBody().getHasMoreEntries())) {
                return response;
            } else {
                throw new ResponseValidateException();
            }
        });
    }
}

You can also look at custom RetryPolicy (for example CircuitBreakerRetryPolicy) classes to add them in your RetryTemplate bean for your cases.

Related