业务里如果无法避免远程调用,那么肯定是需要进行异步调用,因为无法保证远程接口的及时响应性,CompletableFuture异步编排特性可以用到,task1和task2任务结束后,执行task3。
CompletableFuture<Object> task1 =CompletableFuture.supplyAsync(() -> {
System.out.println("单号check线程" + Thread.currentThread().getId());
//单号check接口 校验失败抛出异常
return "账单实体信息";
}, executor);
CompletableFuture<Object> task2 = CompletableFuture.supplyAsync(() -> {
System.out.println("收款单生成线程" + Thread.currentThread().getId());
try {
//收款单生成
return “账单编号”;
Thread.sleep(3000);
System.out.println("任务2结束:");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, executor);
//task1、task2 执行完执行task3 ,需要感知task1和task2的执行结果
CompletableFuture<Boolean> future = task1.thenCombineAsync(task2, (t1, t2) -> {
System.out.println("账单金额回写线程" + Thread.currentThread().getId());
// t1 、t2返回判断
//回写返回结果
return ture;
}, executor);