Edwin Dalorzo
Edwin Dalorzo

Reputation: 78639

How to programmatically stop a Vert.x verticle?

Suppose I have a verticle somewhat like this (intentionally simplified to make it easier to explain my question).

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());
   }
}

Now imagine that MyService is event driven, and I would like to stop the verticle when certain event happens in the service.

class MyService {

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

Does anyone with more experience with Vert.x knows how to accomplish that? Or perhaps some advise for me on what is an alternative way to do this right?

Upvotes: 1

Views: 1665

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17731

Let's divide this into two parts:

  1. How to undeploy verticle
  2. How to communicate between your business logic and VertX

Here's an example of a verticle undeploying itself after 5 seconds.

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");
    }
}

You simply call undeploy() with verticle identifier: deploymentID().

Now, you don't want to pass your VertX instance to your service for sure.
Instead, you can have interface:

interface UndeployableVerticle {
    void undeploy();
}

That you implement and pass to your service:

public class ServiceVerticle extends AbstractVerticle implements UndeployableVerticle  {

   private MyService myService = new MyService(this);

   ...
}

Then call it like so:

public void onEvent(Event event) {
   this.verticle.undeploy();
}

Upvotes: 2

Related Questions