CompletableFuture
1.介绍及语法格式
CompletableFuture是java8新增的并发工具类,继承了FutureTask的同步任务的特点,同时新增了异步调用的特点,说简单点就是它可以让代码一起运行,不需要一个个运行
var aFuture = CompletableFuture.supplyAsync(()->{ //..... return xxx; }); var bFuture = CompletableFuture.supplyAsync(()->{ //..... return xxx; }); var cFuture = CompletableFuture.supplyAsync(()->{ //..... return xxx; }); //并行处理 CompletableFuture .allOf(aFuture, bFuture, cFuture) .join(); //取值 var a= aFuture.get(); var b= bFuture.get(); var c= cFuture.get();
2.案例
调用的接口是:/index/getBaseInfo
请求方式:Get请求
查询对应的后端接口位置:
未使用CompletableFuture方法
IndexController层
/** * 首页--基础数据统计 * @param beginCreateTime * @param endCreateTime * @return */ @GetMapping("/getBaseInfo") public AjaxResult getBaseInfo(@RequestParam("beginCreateTime") String beginCreateTime, @RequestParam("endCreateTime") String endCreateTime){ return AjaxResult.success(reportService.getBaseInfo(beginCreateTime,endCreateTime)); }
查看对应的service层
IReportService
/** * 首页基本数据展示 * @param beginCreateTime * @param endCreateTime * @return */ IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime);
可以看到返回的VO对象是一个叫IndexBaseInfoVO的类
package com.huike.report.domain.vo; import lombok.Data; /** * 首页基本数据VO对象 */ @Data public class IndexBaseInfoVO { private Integer cluesNum=0; //线索数目 private Integer businessNum=0; //商机数目 private Integer