I'm trying to make 500 REST calls (POST) to an API using Spring Boot. Currently I'm using a thread pool
using callable - executor service
since I require the response from the POST call as well. Is there a more efficient way to do this within Spring Boot?
edit - This is a IO Intensive Task
CodePudding user response:
You can simply use WebClient, as it's non-blocking by design.
see e.g.: https://newbedev.com/springboot-how-to-use-webclient-instead-of-resttemplate-for-performing-non-blocking-and-asynchronous-calls But there are lots of other resources on the web.
However... if you're using RestTemplate:
@Service
public class AsyncService {
private final RestTemplate restTemplate;
public AsyncService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Async
public CompletableFuture<ResponseDto[]> callAsync(RequestDto requestDto) {
ResponseDto[] responseDtos = restTemplate.postForObject("someUrl", requestDto, ResponseDto[].class);
return CompletableFuture.completedFuture(responseDtos);
}
}
Then you can simply loop though all requests from whatever place is ideal for your context using standard Java Future mechanisms.
Just make sure to add @EnableAsync to your application
A more detailed tutorial can be found here: https://spring.io/guides/gs/async-method/