2
votes

I am using the Spring4 AsyncRestTemplate to make calls to an External REST API service.

The method below is from a Spring @Service class. The AsyncRestTemplate is autowired from a Spring @Bean.

In the method, I register callbacks on the ListenableFuture response from the REST API call.

I don't use the returned ListenableFuture except for unit tests. The callbacks will handle the actual actions I want to take based on request success or failure.

ExternalServiceImpl.class

public ListenableFuture<ResponseEntity<ResponseBody>> makeExternalCall(RequestBody requestBody) {

            HttpEntity<RequestBody> request = new HttpEntity<>(RequestBody, getDefaultHeaders());

            ListenableFuture<ResponseEntity<ResponseBody>> responseEntity = asyncRestTemplate.exchange(serviceUri.toUriString(), HttpMethod.POST, request, ResponseBody.class);

            responseEntity.addCallback(
                    (onSuccess) -> System.out.println("Success"), 
                    (onFailure) -> onFailure.printStackTrace()
            );

            return responseEntity;
    }

I plan on using the @EnableAsync annotation and setting up a ThreadPoolTaskExecutor as well as adding an @async annotation to the method in a manner similar to the procedure described here: Spring Asynchronous Methods

Questions

  • Is this redundant? Is there an additional benefit to scaling when making the method async even though I'm using an AsyncRestTemplate?

  • Is there anything considered best practice that I'm missing in
    implementing this pattern?

  • Is there anything to watch out for?

1

1 Answers

0
votes

@Async doesn't actually do anything until you add the @EnableAsync annotation to your application. When that happens, any code calling your makeExternalCall method will immediately return, and spring will look for a TaskExecutor bean to run the whole method asynchronously (rather than just your asyncRestTemplate service being the only async part of your code currently).

More info on the spring website: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html