final Stopwatch stopwatch = Stopwatch.createStarted();
CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
try {
// 这里模拟微服务A的查询接口
System.out.println("A======" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return RandomStringUtils.randomAlphabetic(10);
}).thenCombineAsync(
CompletableFuture.supplyAsync(() -> {
try {
// 这里模拟微服务B的查询接口
System.out.println("completablefutureB======" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
return RandomStringUtils.randomAlphabetic(20);
})
, (r1, r2) -> {
// 合并两个查询结果
return r1 + " = " + r2;
});
System.out.println("main======" + Thread.currentThread().getName());
System.out.println(result.get());
stopwatch.stop();
// 整体请求时间以最长的来定
System.out.println("senconds:" + stopwatch.elapsed(TimeUnit.SECONDS));
所有评论(0)