Combining compleblefuture with Sleuth of Spring, combining tool classes with allOf and anyOf

Keywords: Programming Spring WebFlux

Series Catalog:

  1. Thinking and comparison in the application of Spring WebFlux
  2. Completabilefuture and Spring's Sleuth combination tool class
  3. Some optimization thinking in the process of using anyOf by CommpetableFuture
  4. Combining compleblefuture with Sleuth of Spring, combining tool classes with allOf and anyOf

The previously implemented completable futurewithspan cannot directly use anyOf or allOf. Because to view the source code:

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

The andTree here is an internal method, which is actually a recursive parallel connection of all the incoming completable future. How does this recursion end? It is mainly concluded by the following methods

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

Unfortunately, this method is final, the modified field is also an internal field, and the completable futurewithspan is implemented based on the agent, so it is not feasible to directly use the original allOf and anyOf, and it is also not feasible to inherit and overwrite bipush.

We have to realize our own:

public static CompletableFutureWithSpan<Void> allOf(Tracer tracer, CompletableFutureWithSpan<?>... cfs) {
        //Need transformation
        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) {
    //Need transformation
    CompletableFuture[] completableFutures = Arrays.stream(cfs).map(completableFutureWithSpan -> completableFutureWithSpan.completableFuture).collect(Collectors.toList()).toArray(new CompletableFuture[0]);
    return from(CompletableFuture.anyOf(completableFutures), tracer);
}

Posted by phpnewbie81 on Fri, 22 Nov 2019 11:02:07 -0800