[英]Using Spring4 AsyncRestTemplate in a method which uses an @Async annotation
I am using the Spring4 AsyncRestTemplate to make calls to an External REST API service. 我正在使用Spring4 AsyncRestTemplate调用外部REST API服务。
The method below is from a Spring @Service class. 下面的方法来自Spring @Service类。 The AsyncRestTemplate is autowired from a Spring @Bean .
AsyncRestTemplate是通过Spring @Bean自动装配的。
In the method, I register callbacks on the ListenableFuture response from the REST API call. 在该方法中,我在REST API调用的ListenableFuture响应上注册了回调。
I don't use the returned ListenableFuture except for unit tests. 除了单元测试外,我不使用返回的ListenableFuture 。 The callbacks will handle the actual actions I want to take based on request success or failure.
回调将根据请求成功或失败处理我要采取的实际操作。
ExternalServiceImpl.class 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 我计划使用@EnableAsync批注并设置ThreadPoolTaskExecutor以及以类似于此处描述的过程的方式向方法中添加@async批注: Spring异步方法
Questions 问题
Is this redundant? 这多余吗? Is there an additional benefit to scaling when making the method async even though I'm using an AsyncRestTemplate ?
即使我正在使用AsyncRestTemplate ,使方法异步时缩放也还有其他好处吗?
Is there anything considered best practice that I'm missing in 有什么我认为缺少的最佳实践吗?
implementing this pattern? 实现这种模式?
Is there anything to watch out for? 有什么需要注意的吗?
@Async
doesn't actually do anything until you add the @EnableAsync
annotation to your application. @Async
直到你添加实际上并没有做任何事情@EnableAsync
注释到您的应用程序。 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). 发生这种情况时,任何调用
makeExternalCall
方法的代码都将立即返回,并且spring会寻找TaskExecutor
bean来异步运行整个方法(而不仅仅是asyncRestTemplate
服务是当前代码中唯一的异步部分)。
More info on the spring website: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html 春季网站的更多信息: http : //docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.