Skip to content

Instantly share code, notes, and snippets.

@stream-iori
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save stream-iori/cee5f5de92dca363243f to your computer and use it in GitHub Desktop.

Select an option

Save stream-iori/cee5f5de92dca363243f to your computer and use it in GitHub Desktop.
Warp Handler as CompleatableFuture
//假设你是做多次eb通信, 而且address2必须依赖address1的结果.
CompletableFuture<String> future = new CompletableFuture<>();
vertx.eventBus().send("address1", "a", (Message<String> event) -> {
future.complete(event.body()); //把address1返回的值放入future
});
vertx.eventBus().send("address2", "b", (Message<String> event) -> {
//这里s 是刚才上面address1返回的值,这里累加起来
future.thenCompose(s -> CompletableFuture.completedFuture(s + event.body()));
});
//最后打印结果,避免了两个bus的嵌套
future.whenComplete((result, throwable) -> {
if (throwable != null) throwable.printStackTrace();
else System.out.println(result);
});
//分开写,然后组合在一起
CompletableFuture<String> future1 = new CompletableFuture<>();
vertx.eventBus().send("address1", "a", (Message<String> event) -> {
future1.complete(event.body()); //把address1返回的值放入future
});
CompletableFuture<String> future2 = new CompletableFuture<>();
vertx.eventBus().send("address2", "b", (Message<String> event) -> {
future2.complete(event.body()); //把address2返回的值放入future
});
//future1组合future2的结果, 并调用一个匿名函数
future1.thenCombine(future2, (s, s2) -> s + s2).whenComplete((result, throwable) -> {
if (throwable != null) throwable.printStackTrace();
else System.out.println(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment