SpringBoot中異步調用方法并接收傳回值
需求
調用多個接口,從每個接口中擷取需要的一些字段,最後把從各個接口中擷取到的字段組合成一個複雜對象。
設計
當調用多個接口時,必須異步調用,否則難以保證性能。
串行調用 A + B + C、異步調用 MAX(A,B,C)
異步調用多個接口,最終的耗時取決于時間最長的那個接口。
使用線程池實作異步執行方法;使用Future類包裝線程執行結果。
代碼概要
public void mainThread() {
// 1.建立要組裝的複雜對象
ComplexObject complexObject = new complexObject();
// 2.異步調用多個接口
Future<UserInfoResponse> userInfoResponseFuture = callInterfaceService.queryUserInfo();
Future<CardInfoResponse> CardInfoResponseFuture = callInterfaceService.queryCardInfo();
// 3.get方法阻塞等待異步線程執行結果
try {
UserInfoResponse userInfoResponse = userInfoResponseFuture.get();
if (userInfoResponse == null) {
log.info("### userInfo 接口調用失敗");
} else {
setComplexObjectByUserInfoResponse(complexObject, userInfoResponse);
}
} cathc (Exception e) {
log.info("### 異步調用 userInfo 接口 出現異常", e);
}
try {
CardInfoResponse cardInfoResponse = CardInfoResponseFuture.get();
if (cardInfoResponse == null) {
log.info("### cardInfo 接口調用失敗");
} else {
setComplexObjectByCardInfoResponse(complexObject, cardInfoResponse);
}
} cathc (Exception e) {
log.info("### 異步調用 cardInfo 接口 出現異常", e);
}
// 4.使用組裝好的對象
useComplexObject(complexObject);
}
........................................................................................................
@Async
public Future<UserInfoResponse> queryUserInfo() {
......
Response response = callRpcService.callUserInfo(request);
if (!response.isSuccess) {
log.info("### 調用 userInfo 底層接口失敗");
return new AsyncResult<>(null);
}
return new AsyncResult<>(response);
}
...... 省略後續代碼 ......