背景:开发中遇到主流程中需要同时处理多个流程时,并且对耗时和性能有高要求
推荐:CompletableFuture
用法:多任务时,支持同步异步执行,并行,串行,顺序执行,有无结果返回,结果统一处理,单独处理结果等
,具体方法百度CompletableFuture语法
案例:👇👇👇👇👇
List<Integer> mergeAlarmIds = mergeAlarmProcessList.stream().map(MergeAlarmProcess::getMergeAlarmId).collect(Collectors.toList());
List<MergeAlarm> mergeAlarmList = new ArrayList<>();
List<List<Integer>> departmentGroup = Lists.partition(mergeAlarmIds, 50);
List<CompletableFuture<List<MergeAlarm>>> futures = new ArrayList<>();
for (List<Integer> integers : departmentGroup) {
futures.add(CompletableFuture.supplyAsync(() ->
mergeAlarmService.getMergeAlarmListByCondition(
this.mergeAlarmService.condition()
.in(MergeAlarm.ID,integers)
));
}
CompletableFuture[] collect = futures.toArray(new CompletableFuture[futures.size()]);
CompletableFuture.allOf(collect).join();
for (CompletableFuture future : collect) {
try {
mergeAlarmList.addAll((List<MergeAlarm>) future.get());
} catch (Exception e) {
log.error("查询数据失败:{}", e.getMessage(), e);
}
}