由于業(yè)務(wù)中會(huì)進(jìn)行多次接口請(qǐng)求,每次以串行方式請(qǐng)求會(huì)導(dǎo)致整個(gè)流程耗時(shí)邊長(zhǎng)。采用并發(fā)請(qǐng)求方式宋彼,并在最終聚合請(qǐng)求結(jié)果睦裳≡旃可以大大縮短整個(gè)運(yùn)行時(shí)長(zhǎng)
@GetMapping("/test")
public ResponseMessage test(){
long t1 = System.currentTimeMillis();
List<String> results = new ArrayList<>();
List<String> list = Lists.newArrayList(
"http://localhost:8080/api/ceshi?id=1",
"http://localhost:8080/api/ceshi?id=2",
"http://localhost:8080/api/ceshi?id=3",
"http://localhost:8080/api/ceshi?id=4",
"http://localhost:8080/api/ceshi?id=5"
);
List<CompletableFuture<String>> futureTasks = new ArrayList<>(list.size());
for (String url : list) {
futureTasks.add(CompletableFuture.supplyAsync(() -> HttpUtil.get(url)));
}
for (CompletableFuture<String> futureTask : futureTasks) {
results.add(futureTask.join());
}
System.out.println(results);
long t2 = System.currentTimeMillis();
return ResponseMessage.success("耗時(shí):"+ (t2-t1));
}