欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > 39、CompletableFuture的使用

39、CompletableFuture的使用

2025/7/3 8:49:14 来源:https://blog.csdn.net/weixin_44794260/article/details/141168222  浏览:    关键词:39、CompletableFuture的使用

CompletableFuture的使用

      • API使用
      • 案例实战

API使用

  • 简单执行

public static void test1() throws Exception {CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {return "hello";});System.out.println(Thread.currentThread().getName() + ":" +stringCompletableFuture.get());}
  • 结果作为下一个的参数

/*** 结果作为下一个参数  无返回值* @throws Exception*/public static void test3() throws Exception {CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {return "hello";});CompletableFuture<Void> stringCompletableFuture1 = stringCompletableFuture.thenAccept(s -> {System.out.println(s + " world");});System.out.println(Thread.currentThread().getName() + ":" +stringCompletableFuture1.get());}/*** 结果作为下一个参数  又返回值* @throws ExecutionException* @throws InterruptedException*/public static void test2() throws Exception {CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {return "hello";});CompletableFuture<String> stringCompletableFuture1 = stringCompletableFuture.thenApply(s -> {return s + " world";});System.out.println(Thread.currentThread().getName() + ":" +stringCompletableFuture1.get());}
  • thenCompose的使用(类似于flatmap)
public static void test4() throws Exception {ProductService productService = new ProductService();ProductDetailService productDetailService = new ProductDetailService();
//      同一个线程执行
//        CompletableFuture<Product> productCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            String name = productService.getProduct(1);
//            Product product = new Product();
//            product.setName(name);
//            return product;
//        }).thenApply(product -> {
//            String desc = productDetailService.getProduct(1);
//            product.setDesc(desc);
//            return product;
//        });
//        System.out.println(Thread.currentThread().getName() + ":" +productCompletableFuture.get());//不同的线程执行CompletableFuture<CompletableFuture<Product>> completableFutureCompletableFuture = CompletableFuture.supplyAsync(() -> {String name = productService.getProduct(1);Product product = new Product();product.setName(name);return product;}).thenApply(new Function<Product, CompletableFuture<Product>>() {@Overridepublic CompletableFuture<Product> apply(Product product) {return CompletableFuture.supplyAsync(() -> {String desc = productDetailService.getProduct(1);product.setDesc(desc);return product;});}});System.out.println(Thread.currentThread().getName() + ":" +completableFutureCompletableFuture.get().get());
////不同的线程执行
//        CompletableFuture<Product> productCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
//            String name = productService.getProduct(1);
//            Product product = new Product();
//            product.setName(name);
//            return product;
//        }).thenCompose((Function<Product, CompletableFuture<Product>>) product -> CompletableFuture.supplyAsync(() -> {
//            String desc = productDetailService.getProduct(1);
//            product.setDesc(desc);
//            return product;
//        }));
//        System.out.println(Thread.currentThread().getName() + ":" +productCompletableFuture1.get());}
  • 多个Future 如何处理他们的一些聚合关系呢
    • allOf
      • 返回值是CompletableFuture<Void>类型
      • 因为allOf没有返回值,所以通过thenApply获取CompletableFuture的执行结果
      • 使用场景:请求多个接口 聚合结果
    • anyOf
      • 只要有任意一个CompletableFuture结束,就可以做接下来的事情,不像allOf要等待所有的CompletableFuture都结束才做接下来的事情
      • 每个CompletableFuture的返回值类型都不相同,无法判断是什么类型
      • 所以anyOf返回值是CompletableFuture<Object>类型
      • 使用场景:多个机房 机器配置以及压力不一样 请求同一个接口 返回参数也一样 ,使用anyOf同步请求所有机房,然后谁最新返回 就直接使用返回结果
 /*** 多个Future 如何处理他们的一些聚合关系呢* allOf  anyOf* @throws Exception*/public static void test6() throws Exception {CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(Thread.currentThread().getName() + ":" + "future1");return "future1";});CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(Thread.currentThread().getName() + ":" + "future2");return "future2";});CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(Thread.currentThread().getName() + ":" + "future3");return "future3";});//等待所有任务完成
//        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3);
//        System.out.println("begin" + LocalDateTime.now());
//        voidCompletableFuture.join();
//        if (voidCompletableFuture.isDone()){
//            System.out.println("任务全部完成");
//        }
//        System.out.println("end" + LocalDateTime.now());System.out.println("-----------------------------");//等待任何一个任务完成CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(future1, future2, future3);System.out.println("begin" + LocalDateTime.now());objectCompletableFuture.join();if (objectCompletableFuture.isDone()){System.out.println("有任务完成");}System.out.println("end" + LocalDateTime.now());}

案例实战

  • 背景
    • 微服务架构,接口单一职责,一个页面打开会涉及多个模块需要同时调用
    • 由于需要同时建立多个连接,中间会有性能损耗,部分页面需要使用聚合接口
    • 则可以使用CompletableFuture聚合多个响应结果一次性返回
      • 优点
        • 减少建立连接数量
        • 网关和服务端可以处理更多的连接
      • 缺点
        • 如果接口性能差异大,则容易性能好的接口被性能查的拖垮
        • 需要开发更大接口,数据量大则需要更大的带宽
    • 其他场景
      • 爬虫业务多个URL并行爬取
      • 商品详情页信息组装
      • 业务聚合接口:用户信息(积分基本信息,权限)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词