刚开始使用Mutiny,通过指南(https://smallrye.io/smallrye-mutiny/guides)工作。而且,就我在文档中读取的内容而言,调用方法是异步(https://smallrye.io/smallrye-mutiny/getting-started/observing-events)。
但是,使用一个小片段,就会发现call方法正在阻止执行,据我理解,也不是异步的。错误/误解在哪里?
Uni.createFrom().item("bla")
.onItem().invoke(i -> LOG.info("before call"))
.onItem().call(i -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Uni.createFrom().voidItem();
}
)
.subscribe().with(i -> LOG.info("after call process. result=" + i));测井输出
11:40:11.026 INFO [main] ....mutiny.vertx.HelloUni - before call
11:40:16.032 INFO [main] ....mutiny.vertx.HelloUni - after call process. result=bla发布于 2022-05-12 20:31:18
每个订阅者(这里我们有一个来自主线程的订阅者)将尝试(单独)解析Uni。当它到达call lambda时,它只是在Thread.sleep调用中阻塞,然后在链中创建新的Uni。
传递给.call或.transformToUni的函数不应该阻塞内部的I/O (sleep正在这样做),而是启动I/O请求并立即返回Uni。
顺便说一句,如果我们想发布延迟(非阻塞),我们可以这样做:
Uni<String> uni1 = Uni.createFrom().item("bla")
.onItem().invoke(s -> logger.info("before call"))
.onItem().delayIt().by(Duration.ofSeconds(3));
uni1.subscribe().with(s -> logger.info("after: result=" + s));
logger.info("main continues its work ...");
...发布于 2022-05-12 19:03:28
这是因为没有自动神奇地使您的代码异步.
在这里,在返回Uni之前阻塞线程,因此完全可以预期您在订阅时会观察到这样的行为。
https://stackoverflow.com/questions/71882523
复制相似问题