首先定义一个类,该类封装批量请求参数
public class Result { private Integer id; private String requestParam; private Date date; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRequestParam() { return requestParam; } public void setRequestParam(String requestParam) { this.requestParam = requestParam; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
接下来模拟批量调用其他服务接口:
import com.google.common.collect.Lists; import org.apache.commons.collections.CollectionUtils; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class ManyThreadCallTest { private static final int dataSize = 50; public static void main(String[] args){ // 模拟从数据库查询数据 List<Result> params = queryFromDB(); // 2,模拟多线程批量调用接口 ManyThreadCall(params); } // 模拟从数据库查询请求入参记录 private static List<Result> queryFromDB() { List<Result> resultLists = Lists.newArrayList(); for (int i = 0; i < dataSize; i++) { Result resultDto = new Result(); resultDto.setRequestParam("WJ00000" + i); resultLists.add(resultDto); } return resultLists; } private static void ManyThreadCall(List<Result> params) { Long startTime= System.currentTimeMillis(); List<Result> resultLists = Lists.newArrayList(); // params集合拆分,List<List<Result>>里面每个List<Result>包含3条记录,这里也可以根据业务情况做调整,调整为4或者5都可以。 List<List<Result>> partList = Lists.partition(params,3); for(List<Result> requestParms:partList){ List<Result> resultData = getResultData(requestParms); if(CollectionUtils.isNotEmpty(resultData)){ resultLists.addAll(resultData); } } System.out.println("ManyThreadCall 花费时间:"+(System.currentTimeMillis()-startTime)); } // CompletableFuture多线程调用并返回值 public static List<Result> getResultData(List<Result> params) { List<CompletableFuture<Result>> completableFutureList = Lists.newArrayList(); params.stream().forEach(param -> { try { CompletableFuture<Result> future = CompletableFuture.supplyAsync(() -> callRemoteInterface(param)); completableFutureList.add(future); } catch (Exception e) { System.out.println("callRemoteInterface fail,requestParam:"+param.getRequestParam()); } }); List<Result> results = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList()); return results; } // 伪代码模拟调用外部接口 private static Result callRemoteInterface(Result resultDto) { try { // 这里假设调接口花费2秒 TimeUnit.SECONDS.sleep(2L);//call壹次花費2秒鐘 } catch (InterruptedException e) { e.printStackTrace(); } return resultDto; } }