首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Uni等待Vertx eventBus消息

Uni等待Vertx eventBus消息
EN

Stack Overflow用户
提问于 2022-05-08 07:50:38
回答 1查看 282关注 0票数 0

我有两个端点:

代码语言:javascript
复制
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/waitForEvent")
    public Uni<Object> waitForEvent() {
        return Uni.createFrom().emitter(em -> {
            //wait for event from eventBus
    //            eventBus.consumer("test", msg -> {
    //                System.out.printf("receive event: %s\n", msg.body());
    //                em.complete(msg);
    //            });
        }).ifNoItem().after(Duration.ofSeconds(5)).failWith(new RuntimeException("timeout"));
    }
    
    @GET
    @Path("/send")
    public void test() {
        System.out.println("send event");
        eventBus.send("test", "send test event");
    }

只有当waitForEvent()接收到来自eventBus的事件时,它才会完成。我如何使用vertx和哗变来实现这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-09 06:07:27

通常,我们避免这种模式,并使用事件总线的请求/应答机制:

代码语言:javascript
复制
@GET
@Path("/send")
public Uni<String> test() {
   return bus.<String>request("test", name)        
        .onItem().transform(Message::body)
        .ifNoItem().after(Duration.ofSeconds(5)).failWith(new RuntimeException("timeout"));
}

当使用两个端点实现时(如问题中所示),它可能会变得更加复杂,就好像您有多个对/waitForEvent端点的调用一样,您需要确保每个“使用者”都得到消息。

这仍然是可能的,但它需要这样的东西:

代码语言:javascript
复制
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/waitForEvent")
public Uni<String> waitForEvent() {
  return Uni.createFrom().emitter(emitter -> {
    MessageConsumer<String> consumer = bus.consumer("test");
      consumer.handler(m -> {
      emitter.complete(m.body());
      consumer.unregisterAndForget();
   })
        .ifNoItem().after(Duration.ofSeconds(5)).failWith(new RuntimeException("timeout"));

}
    
@GET
@Path("/send")
public void test() {
  bus.publish("test", "send test event");
}

确保使用事件总线的io.vertx.mutiny.core.eventbus.EventBus变体。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72159054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档