How to use AsyncRestTemplate to make multiple calls simultaneously?

前端 未结 6 2157
耶瑟儿~
耶瑟儿~ 2021-02-18 22:42

I don\'t understand how to use AsyncRestTemplate effectively for making external service calls. For the code below:

class Foo {

    public void doS         


        
6条回答
  •  萌比男神i
    2021-02-18 23:14

    You might want to use CompletableFuture class (javadoc).

    1. Transform your calls into CompletableFuture. For instance.

      final CompletableFuture> cf = CompletableFuture.supplyAsync(() -> {
          try {
              return future.get();
          } catch (InterruptedException | ExecutionException e) {
              throw new RuntimeException(e);
          }
      });
      
    2. Next call CompletableFuture::allOf method with your 3 newly created completable futures.

    3. Call join() method on the result. After the resulting completable future is resolved you can get the results from each separate completable future you've created on step 3.

提交回复
热议问题