结合CompletableFuture与Spring的Sleuth结合工具类与allOf以及anyOf

系列目录:

  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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值