CommpetableFuture使用anyOf过程中的一些优化思考

Stella981
• 阅读 707

系列目录:

  1. Spring WebFlux运用中的思考与对比
  2. CompletableFuture与Spring的Sleuth结合工具类
  3. CommpetableFuture使用anyOf过程中的一些优化思考
  4. 结合CompletableFuture与Spring的Sleuth结合工具类与allOf以及anyOf

CompetableFuture的

上一篇我们讲述了如何将CompletableFuture与Spring Sleuth结合起来。这篇我们继续优化CompletableFuture

CompletableFuture的allOf

首先我们看看allOf的定义:

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
    // ...
}

这个方法接受若干个返回不同类型的CompletableFuture为参数, 返回一个返回为空(Void)的CompletableFuture。也就是说,这个方法其实就是返回一个在所有参数完成之后也完成的返回为空(Void)的CompletableFuture,也就是充当一个signaling device

这个方法很好,尤其是并发获取多种io的结果的时候。但是用这个方法,带来了很多不便,最大的不便就是,返回是Void,而不是所有的参数的返回。这样导致我们,需要在聚合这些结果的那个服务方法里面,把最终结果封装好,否则,获取的就是一个Void。举个例子:

假设我的一个服务方法的返回是多个接口在使用,这个方法需要同时调用三个io等待他们都返回时,利用这三个io的返回,拼装成接口需要的字段。对于这个场景,我们可以有两种写法,第一种是基于回调的写法,第二种是基于返回的写法,两种都OK,看个人习惯,我个人倾向于基于返回的写法,这样代码是瀑布式的,基于回调的会导致多层嵌套,导致代码可读性降低。

** 结果类:**

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class Result {
   private String string;
   private List<String> strings;
   private List<Integer> integers;
}

** 基于回调:**

public static void baseOnCallBack(CompletableFuture<Result> resultCompletableFuture) {
   CompletableFuture<List<String>> result1 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return Lists.newArrayList("a", "b", "c");
   });
   CompletableFuture<List<Integer>> result2 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return Lists.newArrayList(1, 2, 3);
   });
   CompletableFuture<String> result3 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return "hash-test";
   });

   CompletableFuture.allOf(result1, result2, result3).thenAcceptAsync(v -> {
       resultCompletableFuture.complete(Result.builder()
               //一定存在的,因为已经完成了
               .string(result3.join())
               .strings(result1.join())
               .integers(result2.join())
               .build());
   });
}

** 基于返回:**

public static CompletableFuture<Result> baseOnReturn() {
   CompletableFuture completableFuture = new CompletableFuture();
   CompletableFuture<List<String>> result1 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return Lists.newArrayList("a", "b", "c");
   });
   CompletableFuture<List<Integer>> result2 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return Lists.newArrayList(1, 2, 3);
   });
   CompletableFuture<String> result3 = CompletableFuture.supplyAsync(() -> {
       //模拟io
       try {
           TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000));
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       return "hash-test";
   });
   CompletableFuture.allOf(result1, result2, result3).thenAcceptAsync(v -> {
       completableFuture.complete(Result.builder()
               //一定存在的,因为已经完成了
               .string(result3.join())
               .strings(result1.join())
               .integers(result2.join())
               .build());
   });
   return completableFuture;
}

基于回调的接口使用结果:

CompletableFuture completableFuture = new CompletableFuture();
baseOnCallBack(completableFuture);
completableFuture = completableFuture.thenAcceptAsync(result -> {
    System.out.println("baseOnCallback: " + result);
});

基于返回的接口使用结果:

CompletableFuture<Void> voidCompletableFuture = baseOnReturn().thenAcceptAsync(result -> {
    System.out.println("baseOnReturn: " + result);
});

可以看出,一层嵌套也是基于返回的代码看上去更优雅。

我们再来思考下,如果allOf中的所有CompletableFuture都返回的是同一个类型的结果,例如String,那么可不可以让allOf直接返回List<String>呢?

我们可以将一个allOf变成多个allOf这么实现:

public static <T> CompletableFuture<List<T>> allOf(Collection<CompletableFuture<T>> futures) {
    return futures.stream().collect(Collectors.collectingAndThen(
                    Collectors.toList(),
                    l -> CompletableFuture.allOf(l.toArray(new CompletableFuture[0]))
                            .thenApply(v -> l.stream().map(CompletableFuture::join).collect(Collectors.toList()))
            )
    );
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Spring WebFlux运用中的思考与对比
系列目录:1.SpringWebFlux运用中的思考与对比(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fblog.csdn.net%2Fzhxdick%2Farticle%2Fdetails%2F103035149)2.CompletableFuture与Sprin
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
CompletableFuture与Spring的Sleuth结合工具类
系列目录:1.SpringWebFlux运用中的思考与对比(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fblog.csdn.net%2Fzhxdick%2Farticle%2Fdetails%2F103035149)2.CompletableFuture与Sprin
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这