I don\'t understand how to use AsyncRestTemplate
effectively for making external service calls. For the code below:
class Foo {
public void doS
Simply don't call blocking get()
before dispatching all of your asynchronous calls:
class Foo {
public void doStuff() {
ListenableFuture> future1 = asyncRestTemplate
.getForEntity(url1, String.class);
ListenableFuture> future2 = asyncRestTemplate
.getForEntity(url2, String.class);
ListenableFuture> future3 = asyncRestTemplate
.getForEntity(url3, String.class);
String response1 = future1.get();
String response2 = future2.get();
String response3 = future3.get();
}
}
You can do both dispatch and get in loops, but note that current results gathering is inefficient as it would get stuck on the next unfinished future.
You could add all the futures to a collection, and iterate through it testing each future for non blocking isDone()
. When that call returns true, you can then call get()
.
This way your en masse results gathering will be optimised rather than waiting on the next slow future result in the order of calling get()
s.
Better still you can register callbacks (runtimes) within each ListenableFuture
returned by AccyncRestTemplate
and you don't have to worry about cyclically inspecting the potential results.