如何在Vert.x中有效地编写复合协调

时间:2017-06-22 14:36:57

标签: java vert.x

我想知道在Vert.x中以异步方式运行以下调用集的最佳方法是什么。

C1: [v1, v2] +--> C2(v1): x --> C2.1(x): xx --|
             |--> C3(v2): y --> C3.1(y): yy --+- C4(xx, yy)

表示法C1: [v1, v2]表示调用C1,它返回一组值[v1, v2]

目前我正在考虑的是:

Future c1 = Future.future();
call_C1(some_input, handler -> {
    // ... do something
    c1.complete([v1, v2]);
});

c1.compose(array -> {
    // process data and then call C2-->C2.1 and C3-->C3.1
    Future c2 = Future.future();
    call_C2(array[0], c2.completer());

    Future c21 = Future.future();
    c2.compose(x -> {
        // process x and then call C2.1
        call_C2_1(x, h -> {
            // process result and complete c21
            c21.complete(xx);
        });
    });

    Future c3 = Future.future();
    call_C3(array[1], c3.completer());

    Future c31 = Future.future();
    c3.compose(y -> {
        // process y and then call C3.1
        call_C3_1(y, h -> {
            c31.complete(yy);
        });
    });

    CompositeFuture.all(c21, c31).setHandler(h -> {
        xx = h.result().resultAt(0);
        yy = h.result().resultAt(1);
        // process xx and yy
    });
});

我希望它是正确的但是有更好,更自然或更有效的方法来结合所有这些呼叫吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

考虑一下RxJava和Vert.x rxified API,这对你来说可能更自然。

以下是一个例子:

  interface C1Result {
    Object v1();

    Object v2();
  }

  static Single<C1Result> C1() {
    return null;
  }

  static Single<Object> C2(Object v1) {
    return null;
  }

  static Single<Object> C21(Object x) {
    return null;
  }

  static Single<Object> C3(Object v2) {
    return null;
  }

  static Single<Object> C31(Object y) {
    return null;
  }

  static Single<Void> C4(Object xx, Object yy) {
    return null;
  }

  public static void main(String[] args) {

    C1().flatMap(c1Result -> {

      Single<Object> xxSingle = C2(c1Result.v1()).flatMap(x -> {
        return C21(x);
      });

      Single<Object> yySingle = C3(c1Result.v2()).flatMap(y -> {
        return C31(y);
      });

      return Single.merge(Single.zip(xxSingle, yySingle, (xx, yy) -> {
        return C4(xx, yy);
      }));

    }).subscribe(v -> {
      // Success
    }, throwable -> {
      // Failure
    });

  }