gpt4 book ai didi

java - Vert.x 从 vertx.executeBlocking 做出 promise

转载 作者:行者123 更新时间:2023-12-02 03:15:52 29 4
gpt4 key购买 nike

我有四个 I/O 操作:ABCD。它们中的每一个都应该使用 vertx.executeBlocking 来执行。我应该有以下行为:

//PSEUDOCODE
waitForExecuteBlocking(A_OPERATION);
thenWaitForAllExecuteBlocking(`B_OPERATION`, `C_OPERATION`, `D_OPERATION`)
/* do something */

我怎样才能实现这种行为?

我在 Vertx Rx 中找不到解决方案。我不想将我的 *_OPERATION 类包装为工作垂直体是有原因的。

最佳答案

我正在添加另一个答案,这次是 Futures。
首先请注意,这些是 Vertx future ,而不是常规的 Java future 。使用正确的导入。
现在看代码:

// I'm running in main(), so everything is static, just for the sake of example
private static Vertx vertx = Vertx.vertx();
public static void main(String[] args) throws InterruptedException {


long start = System.currentTimeMillis();

// In your case it should be operationA(), operationB(), etc
// But I wanted to make the code shorter
CompositeFuture.all(operationA(), operationA(), operationA()).setHandler((r) -> {
if (r.succeeded()) {
// You can even iterate all the results
List<String> results = r.result().list();
for (String result : results) {
System.out.println(result);
}
// This will still print max(operationA, operationB, operationC)
System.out.println("Took me " + (System.currentTimeMillis() - start) + " millis");
}
else {
System.out.println("Something went wrong");
}
});
}


// Return a future, then fulfill it after some time
private static Future<String> operationA() {
Future<String> future = Future.future();

long millis = 1000 + ThreadLocalRandom.current().nextInt(500);
vertx.setTimer(millis, (l) -> {
future.complete("All is good " + millis);
});

return future;
}

关于java - Vert.x 从 vertx.executeBlocking 做出 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40323028/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com