CompletableFuture 批量办卡
需求背景:
每次传入需要办卡的订单的集合,根据每个办卡订单进行办卡操作。
技术要点:线程池,CompletableFuture
入参:
BatchApplyOrderRequestVo {
* 订单id
@ApiModelProperty("etc批量办卡申请订单实体")
@NotNull(groups = {ValidGroup.requireId.class,ValidGroup.edit.class}, message = "etc批量办卡申请订单EtcCardApplyOrderVo")
private List<EtcCardApplyOrderRequestVo> etcCardApplyOrderRequestVoList;
* 紧急联系人
private String contacts;
*紧急联系人电话
private String contactsNumber;
* 应用id
private Long appId;
@ApiModelProperty("etc批量办卡申请订单实体")
@NotNull(groups = {ValidGroup.requireId.class,ValidGroup.edit.class}, message = "etc批量办卡申请订单EtcCardApplyOrderVo")
private List<EtcCardApplyOrderRequestVo> etcCardApplyOrderRequestVoList;
* 紧急联系人
private String contacts;
*紧急联系人电话
private String contactsNumber;
* 应用id
private Long appId;
}
具体实现:
@Autowired private ThreadPoolTaskExecutor executor;//线程池依赖注入
方法
do(vo){
List<EtcCardApplyOrderRequestVo> etcCardApplyOrderRequestVoList = vo.getEtcCardApplyOrderRequestVoList();
List<CompletableFuture> futures = Collections.synchronizedList(new ArrayList<CompletableFuture>()); //创建CompletableFuture集合,
List<CompletableFuture> futures = Collections.synchronizedList(new ArrayList<CompletableFuture>()); //创建CompletableFuture集合,
for (EtcCardApplyOrderRequestVo applyVo : etcCardApplyOrderRequestVoList) {
CompletableFuture<Result> future = CompletableFuture.supplyAsync(() -> applyOrder(applyOrderRequestVo),executor);//根据list集合的每一个对象创建一个线程(supplyAsync有返回值)
futures.add(future);//添加到集合
futures.add(future);//添加到集合
}
//等待所有线程执行完成
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join();
allOf.join();
}
线程池配置
@Configuration public class ThreadPoolTaskExecutorConfig { @Bean public ThreadPoolTaskExecutor batchApplyOrderExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // Java虚拟机可用的处理器数 int corePoolSize = Runtime.getRuntime().availableProcessors(); // 配置核心线程数 executor.setCorePoolSize(corePoolSize); // 配置最大线程数 executor.setMaxPoolSize(corePoolSize * 2 + 1); // 配置队列大小 executor.setQueueCapacity(100); // 空闲的多余线程最大存活时间 executor.setKeepAliveSeconds(3); // 配置线程池中的线程的名称前缀 executor.setThreadNamePrefix("thread-execute-"); // 当线程池达到最大大小时,在调用者的线程中执行任务 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 执行初始化 executor.initialize(); return executor; } }

浙公网安备 33010602011771号