0

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();
}
  • looking at `spring-webflux` label I assume you are using reactive WebClient .In this case you can use `expand` operator https://stackoverflow.com/questions/72290355/how-to-implement-a-call-repetition-until-a-certain-condition-is-met-using-projec/72291465#72291465 – Alex Sep 16 '22 at 01:20
  • Is there any may to modify the request in subsequent calls. Ex. I want to increment pageNumber field with 1 in subsequent calls. – kselvan9000 Sep 16 '22 at 02:39
  • 1
    you have response as an input of the `expand` and could take it from there https://stackoverflow.com/a/71522614/9068895. Or you can use `AtomicInteger` and increment it before the next request – Alex Sep 16 '22 at 04:36

1 Answers1

0

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.

  • Is there any way to modify the request in subsequent calls. Ex. I want to increment pageNumber field with 1 in subsequent calls – kselvan9000 Sep 16 '22 at 03:14
  • @kselvan9000 Yes, for example you can use `retryContext` object from `execute(retryContext -> ...) `method, which extends `AttributeAccessor`. It allows set/get your custom attribute `pageNumber`, which will persist between retries – Alexander Bobryakov Sep 16 '22 at 20:48