系列目录:

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

之前实现的CompletableFutureWithSpan,不能直接使用anyOf或者allOf。因为查看源码:

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
    return andTree(cfs, 0, cfs.length - 1);
}

这里的andTree是内部方法,其实就是递归并联所有传入的CompletableFuture。这个递归如何截止呢?主要由以下的方法结束

final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
    if (c != null) {
        while (result == null) {
            if (tryPushStack(c)) {
                if (b.result == null)
                    b.unipush(new CoCompletion(c));
                else if (result != null)
                    c.tryFire(SYNC);
                return;
            }
        }
        b.unipush(c);
    }
}

非常遗憾,这个方法是final的,修改的field也是内部field,CompletableFutureWithSpan是基于代理实现的,所以直接用原有的allOf还有anyOf是不可行的,继承覆盖bipush也不可行。

只好实现自己的:

public static CompletableFutureWithSpan<Void> allOf(Tracer tracer, CompletableFutureWithSpan<?>... cfs) {
        //需要转换
        CompletableFuture[] completableFutures = Arrays.stream(cfs).map(completableFutureWithSpan -> completableFutureWithSpan.completableFuture).collect(Collectors.toList()).toArray(new CompletableFuture[0]);
        return from(CompletableFuture.allOf(completableFutures), tracer);
}


public static CompletableFuture<Object> anyOf(Tracer tracer, CompletableFutureWithSpan<?>... cfs) {
    //需要转换
    CompletableFuture[] completableFutures = Arrays.stream(cfs).map(completableFutureWithSpan -> completableFutureWithSpan.completableFuture).collect(Collectors.toList()).toArray(new CompletableFuture[0]);
    return from(CompletableFuture.anyOf(completableFutures), tracer);
}
11-22 20:48