How to use AsyncRestTemplate to make multiple calls simultaneously?

前端 未结 6 2045
耶瑟儿~
耶瑟儿~ 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:27

    What I Understand by Your question is You have a predefined asynchronous method and you try to do is call this method asynchoronously using RestTemplate Class.

    I have wrote a method that will help you out to call Your method asynchoronously.

     public void testMyAsynchronousMethod(String... args) throws Exception {
            // Start the clock
            long start = System.currentTimeMillis();
    
            // Kick of multiple, asynchronous lookups
            Future future1 = asyncRestTemplate
            .getForEntity(url1, String.class);;
            Future future2 = asyncRestTemplate
            .getForEntity(url2, String.class);
            Future future3 = asyncRestTemplate
            .getForEntity(url3, String.class);
    
            // Wait until they are all done
            while (!(future1 .isDone() && future2.isDone() && future3.isDone())) {
                Thread.sleep(10); //10-millisecond pause between each check
            }
    
            // Print results, including elapsed time
            System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
            System.out.println(future1.get());
            System.out.println(future2.get());
            System.out.println(future3.get());
        }
    

提交回复
热议问题