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));

 

转载于:https://my.oschina.net/penghaozhong/blog/1862300

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐