java8异步执行

it2025-01-14  7

1.利用java8 CompletableFuture 异步执行

@Resource private Executor threadPoolTaskExecutor; @Autowired private KubernetesService kubernetesService; /** * 更新系统镜像 * * @param version * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public BaseResponse excuteUpdateImage(String version) { String image = "android:" + version; List<VirtualMachine> virtualMachineList = virtualMachineMapper.selectAllNotMaintenanceList(); List<String> nameList = virtualMachineList.stream().map(v -> v.getName()).collect(Collectors.toList()); /** * 异步执行进行 */ List<String> failList = new ArrayList<>(); // 失败结果 List<String> successList = new ArrayList<>(); // 成功结果 CompletableFuture[] cfs = nameList.parallelStream() .map(name -> CompletableFuture .supplyAsync(() -> kubernetesService.setVMImage(name, image), threadPoolTaskExecutor) .whenComplete((s, e) -> { try { if (s.getstatus() == 500) { failList.add(name); } else { successList.add(name); } } catch (Exception e1) { failList.add(name); } })) .toArray(CompletableFuture[]::new); // 等到全部完成 CompletableFuture.allOf(cfs).join(); Map<String, Object> result = new HashMap<>(); result.put("failList", failList); result.put("successList", successList); log.info("更新单台虚拟机系统镜像,image={},version={},result={}", image, version, result); if (CollectionUtils.isEmpty(failList)) { return new BaseResponse(StatusCode.Success, result); } else { return new BaseResponse(StatusCode.Fail, result); } }
最新回复(0)