CompletableFuture是JDK8提出的一个支持非阻塞的多功能的Future,同样也是实现了Future接口
这里只介绍咱们开发中经常用的
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(){
return new ThreadPoolExecutor(20, 200, 10 , TimeUnit.SECONDS, new LinkedBlockingDeque<>(10000), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
}
}
@Autowired
private ThreadPoolExecutor executor;
@RequestMapping(value = "/loanThread", method = RequestMethod.POST)
public RestResponse loanThread(Long orderId){
AceEntity aceEntity = new AceEntity();
//1.将查询的结果返回
CompletableFuture<OrderInfo> orderInfoFuture = CompletableFuture.supplyAsync(() -> {
OrderInfo orderInfo = orderInfoBiz.findById(orderId);;
aceEntity.setOrderID(orderInfo.getId().toString());
return orderInfo;
}, executor);
//取1中的的客户id
CompletableFuture<Void> custInfoFuture = orderInfoFuture.thenAcceptAsync(res -> {
CustInfo custInfo = custInfoBiz.findById(res.getCustInfoId());
aceEntity.setClientID(custInfo.getId().intValue());
}, executor);
try {
//等所有任务执行完再执行主线程
CompletableFuture.allOf(orderInfoFuture,custInfoFuture).get();
} catch (Exception e) {
e.printStackTrace();
}
RestResponse restResponse = aceService.loan(aceEntity);
log.info("loan cost:=======>{}==========mills",CountRunTime.end());
return restResponse;
}
这只是例子 这个是去调用第三方接口需要去查多张表 我将各个查询用异步任务去执行