简体   繁体   中英

Consecutive same Rest API Call using Spring Boot

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM