Spring RestTemplate - async vs sync restTemplate

后端 未结 3 2149
名媛妹妹
名媛妹妹 2020-12-15 06:01

I wrote the following code to test the performance of both the sync RestTemplate and AsyncRestTemplate. I just ran it a few times manually on POSTMAN.

We are just pa

3条回答
  •  情书的邮戳
    2020-12-15 06:42

    I would say that you're missing the real benefits of the AsyncRest here. You should add callbacks to each requests you're sending so that the response will be processes only when available.

    Indeed, the getForEntity method of an AsyncRestTemplate returns a ListenableFuture to which you can connect a callback task. See the official doc ListenableFuture for further information.

    For example in your case it could be:

    for (int i = 0; i < 10; i++) {
         ListenableFuture> response = asyncRestTemplate.getForEntity(references.get(i), String.class);
         response.addCallback(new ListenableFutureCallback>() {
                @Override
                public void onSuccess(ResponseEntity result) {
                    // Do stuff onSuccess 
                    links.add(result.getBody().toString());
                }
    
                @Override
                public void onFailure(Throwable ex) {
                    log.warn("Error detected while submitting a REST request. Exception was {}", ex.getMessage());
                }
            });
    }
    

提交回复
热议问题