In my API I have a service that calls an external API. This external API has a cost per request. Hence I would like to queue up the requests to the external API.
This is how it looks today:
@Component
public class OrderService {
private final WebClient webClient;
public OrderService(WebClient webClient) {
this.webClient = webClient;
}
public Mono<List<Order>> getOrders(List<String> orderNumbers) {
return webClient
.get()
.uri(builder -> builder.queryParam("orderNumbers", String.join(",", orderNumbers)).build())
.retrieve()
.bodyToFlux(Order.class)
.collectList();
}
}
What I would like is to somehow queue up 10 order numbers, and after reaching 10 order numbers in the queue, send the bulk request, and then return the response to all the original requesters.
Let's say OrderService::getOrders
is called three times, first with 4 order numbers, then with 4 additional order numbers, and lastly 4 order numbers again. The first two requests would queue up the total 8 order numbers without calling the external API. Once the third request arrives, we have 12 order numbers in the queue. At this point we will send a request with the first 10 order numbers. The last two remains queued since the maximum order numbers the external API allows is 10.
My API sees a lot of traffic, so it's not an issue to queue and wait, they will not have to wait a long time until the queue has 10 items.
I have tried to read up on how to achieve this with Spring WebFlux, and my research has pointed me to Sinks and Processor. However, I have a hard time wrapping my head around how it all ties together. For instance how I can keep track of which requests requested the specific order numbers.
Could someone more knowledgeable please help me out with how to achieve this?