看这篇文章之前,建议你先去看一下我写的上一篇《RestTemplate调用远程Http服务开发》
一、背景介绍
我们在开发过程中有时候会遇到这样的开发场景:如果调用请求响应比较慢,甚至请求超时,程序就必须等到请求返回以后才能继续执行。然而在某些场合下,我并不需要等待请求的结果,或者我并不关心请求是否执行成功,只需要帮我继续执行之后的逻辑即可,减少响应时间,此时就需要通过异步处理。
在 Spring 3 时代,为了能更优雅地实现HTTP调用,引入了 RestTemplate,其中提供了多种便捷访问远程Http服务的同步调用方法,能够大大提高客户端的编写效率。
在 Spring 4 时代,为了能实现异步地HTTP调用,引入了AsyncRestTemplate,使得编写异步代码和同步代码一样简单。
在 Spring 5 时代,AsyncRestTemplate已经被标注过时,@deprecated as of Spring 5.0, in favor of {@link org.springframework.web.reactive.function.client.WebClient} ,推荐使用Spring 5中的WebClient。WebClient是Spring 5的响应式Web框架Spring WebFlux的一部分,位于spring-webflux项目中。将在后面文章中进行介绍。
二、AsyncRestTemplate介绍
AsyncRestTemplate底层是基于RestTemplate+异步线程池实现的。因此AsyncRestTemplate的很多调用方法跟RestTemplate很相似,主要是返回值不同。
public <T> ListenableFuture<ResponseEntity<T>> getForEntity/postForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> getForEntity/postForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> getForEntity/postForEntity(URI url, Class<T> responseType) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException
public <T> ListenableFuture<ResponseEntity<T>> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException
ListenableFuture是实现异步请求的关键,它继承自并发包下的另一个接口Future,并且巧妙地利用回调来处理异步请求。
ListenableFuture的两个方法签名如下,处理异步请求需要我们手动实现这两个接口(其中的一个)。
void addCallback(ListenableFutureCallback<? super T> callback);
void addCallback(SuccessCallback<? super T> successCallback, FailureCallback failureCallback);
与RestTemplate 相同,AsyncRestTemplate 中最重要的两个方法是exchange和execute。它们需要传入较多的参数,灵活度高自由度大。
三、源码:
废话不多说,举个栗子。
1、配置:
com:
http:
link: http://127.0.0.1:8081/user
connect-timeout: 10000
read-timeout: 60000
2、定义AsyncHttpServiceConfig:
@Configuration
public class AsyncHttpServiceConfig {
public static final Logger log = LoggerFactory.getLogger(AsyncHttpServiceConfig.class);
@Value("${com.http.link:}")
private String httpUrl;
@Value("${com.http.connect-timeout:}")
private int connectTimeout;
@Value("${com.http.read-timeout:}")
private int readTimeout;
@Bean
public AsyncHttpServiceClient asynchttpServiceClient(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//设置链接超时时间
factory.setConnectTimeout(this.connectTimeout);
//设置读取资料超时时间
factory.setReadTimeout(this.readTimeout);
//设置异步任务(线程不会重用,每次调用时都会重新启动一个新的线程)
factory.setTaskExecutor(new SimpleAsyncTaskExecutor());
AsyncHttpServiceClient httpServiceClient = new AsyncHttpServiceClient();
httpServiceClient.setAsyncRestTemplate(new AsyncRestTemplate(factory));
return httpServiceClient;
}
}
3、定义Http客户端异步实现类AsyncHttpServiceClient:
public class AsyncHttpServiceClient {
public static final Logger log = LoggerFactory.getLogger(AsyncHttpServiceClient.class);
private AsyncRestTemplate asyncRestTemplate;
public static final String GET_HTTP_RESOURCE_PATH = "http://localhost:8081/user/queryUserById/{id}";
public String getUserById(int id) throws IOException {
log.info("Start");
ListenableFuture<ResponseEntity<String>> entity = asyncRestTemplate.getForEntity(GET_HTTP_RESOURCE_PATH, String.class, id);
entity.addCallback(new SuccessCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
log.info(result.getBody());
log.info("A");
}
}, new FailureCallback() {
@Override
public void onFailure(Throwable ex) {
log.error(ex.getMessage());
log.info("B");
}
});
log.info("C");
return "End";
}
/**
* @Description: The asyncRestTemplate to set
* @param asyncRestTemplate
*/
public void setAsyncRestTemplate(final AsyncRestTemplate asyncRestTemplate){this.asyncRestTemplate = asyncRestTemplate;}
}
4、运行结果:
2021-06-27 17:11:01.056 INFO 17345 --- [nio-8082-exec-8] com.http.intg.AsyncHttpServiceClient : C
2021-06-27 17:11:01.057 INFO 17345 --- [nio-8082-exec-8] c.h.controller.AsyncRestHttpController : 按员工ID获取员工:End
2021-06-27 17:11:07.553 INFO 17345 --- [cTaskExecutor-1] com.http.intg.AsyncHttpServiceClient : {"code":0,"message":"success","object":{xxx}}
2021-06-27 17:11:07.553 INFO 17345 --- [cTaskExecutor-1] com.http.intg.AsyncHttpServiceClient : A