天天看点

【Future】SpringBoot中异步调用方法并接收返回值SpringBoot中异步调用方法并接收返回值

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);
}

...... 省略后续代码 ......
           

2021/7/13晚 暴雨 写于XX公司