1

假设我有一个有点像这样的垂直(故意简化以更容易解释我的问题)。

public class ServiceVerticle extends AbstractVerticle {

   private MyService myService = new MyService();

   public void start(Future<Void> startFuture) {
      myService.start().addListener(done -> startFuture.complete());
   }

   public void stop(Future<Void> stopFuture) {
      myService.stop().addListener(done -> stopFuture.complete());
   }
}

现在想象这MyService是事件驱动的,我想在服务中发生某些事件时停止垂直。

class MyService {

   public void onEvent(Event event) {
        //here force the service to stop and its associated verticle too
   }
}

有没有对 Vert.x 有更多经验的人知道如何做到这一点?或者也许有一些建议可以告诉我什么是正确的替代方法?

4

1 回答 1

2

让我们把它分成两部分:

  1. 如何取消部署verticle
  2. 如何在您的业务逻辑和 VertX 之间进行通信

这是一个 Verticle 在 5 秒后自行取消部署的示例。

class StoppingVerticle extends AbstractVerticle {

    @Override
    public void start() {

        System.out.println("Starting");
        vertx.setTimer(TimeUnit.SECONDS.toMillis(5), (h) -> {
            vertx.undeploy(deploymentID());
        });
    }

    @Override
    public void stop() {
        System.out.println("Stopping");
    }
}

您只需undeploy()使用 Verticle 标识符调用:deploymentID()

现在,您肯定不想将 VertX 实例传递给您的服务。
相反,你可以有接口:

interface UndeployableVerticle {
    void undeploy();
}

您实现并传递给您的服务:

public class ServiceVerticle extends AbstractVerticle implements UndeployableVerticle  {

   private MyService myService = new MyService(this);

   ...
}

然后像这样调用它:

public void onEvent(Event event) {
   this.verticle.undeploy();
}
于 2018-03-12T10:16:46.273 回答