java的rest异步调用_使用AsyncRestTemplate进行异步调用
背景:
最近項目中需要并發調用c++服務的http接口,問題是同時調用兩個接口時,會發生嚴重阻塞,導致頁面響應慢,還經常遇到接收數據超時,導致RestTemplate報出ReadTimeout錯誤,一味地增加ReadTimeout時間解決不了根本問題。
原使用的方案:
前一個版本中使用的是Feign,雖然響應速度方面還可以,但是唯一不足是,返回的數據只能以String接收,在每一個方法中進行String轉換成java對象的方法。
我是一個比較懶的程序員,不想寫很多無用的重復代碼。所以在這次版本中決定使用RestTemplate,封裝一個RestClient工具類,所有調用第三方接口都通過該工具類提供的方法調用,返回的ResponseEntity通過指定的Class類型進行轉換并返回。
解決方案:
使用AsyncRestTemplate異步調用接口,無阻塞進行請求。下面直接貼代碼。
一、AsyncRestTemplate注冊為Bean,使Spring容器對其進行管理。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.AsyncRestTemplate;
@Configuration
public class RestTemplateConfiguration {
@Bean
public AsyncRestTemplate asyncRestTemplate() {
return new AsyncRestTemplate();
}
}
此次采用的是AsyncRestTemplate默認的構造方法。會默認使用SimpleAsyncTaskExecutor。
二、編寫測試Controller類
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.AsyncRestTemplate;
@RestController
public class WebController {
@Autowired
private AsyncRestTemplate asyncRestTemplate;
@RequestMapping("/demo")
public String demo() {
try {
Thread.sleep(30000);
} catch (Exception e) {
e.printStackTrace();
}
return new Date()+"--->>>30秒。。。。";
}
@RequestMapping("/async")
public String async() {
String url = "http://127.0.0.1:8080/demo";
//調用完后立即返回(沒有阻塞)
ListenableFuture> forEntity = asyncRestTemplate.getForEntity(url, String.class);
//異步調用后的回調函數
forEntity.addCallback(new ListenableFutureCallback>() {
//調用失敗
@Override
public void onFailure(Throwable ex) {
System.err.println("=====rest response faliure======");
}
//調用成功
@Override
public void onSuccess(ResponseEntity result) {
System.out.println("--->async rest response success----, result = "+result.getBody());
}
});
return new Date()+"--->>>異步調用結束";
}
}
三、調用async接口
16:15:20先返回異步調用結束
而調用的方法時16:15:50,即休眠30秒后返回的。
僅供參考,后期對AsyncRestTemplate有更深入的了解繼續更新。。。
總結
以上是生活随笔為你收集整理的java的rest异步调用_使用AsyncRestTemplate进行异步调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 偷梁换柱 暗渡陈仓 一招搞定360安全卫
- 下一篇: python 百度搜索页抽取