How to use AsyncRestTemplate to make multiple calls simultaneously?

前端 未结 6 2056
耶瑟儿~
耶瑟儿~ 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条回答
  •  情话喂你
    2021-02-18 23:20

    I think you are misunderstanding a few things here. When you call the getForEntity method, the requests are already fired. When the get() method of the future object is called, you are just waiting for the request to complete. So in order fire all those three requests on the same subsecond, you just have to do:

    // Each of the lines below will fire an http request when it's executed
    Future> future1 = asyncRestTemplate.getForEntity(url1, String.class);
    Future> future2 = asyncRestTemplate.getForEntity(url2, String.class);
    Future> future3 = asyncRestTemplate.getForEntity(url3, String.class);
    

    After all these codes are run, all the requests are already fired (most probably in the same subsecond). Then you can do whatever you want in the meanwhile. As soon as you call any of the get() method, you are waiting for each request to complete. If they are already completed, then it will just return immediately.

    // do whatever you want in the meantime
    // get the response of the http call and wait if it's not completed
    String response1 = future1.get();
    String response2 = future2.get();
    String response3 = future3.get();
    

提交回复
热议问题