Forwarding requests to different verticle based on path param (Vert.x)

  Kiến thức lập trình

I’m using Vert.x for the first time ever to try to build an API in Java. Right now I can use an eventBus in my main verticle to forward certain routes like /example/:name etc to a handler that sends an eventBus message to it’s respective verticle.

  void helloPOC(RoutingContext context) {
    vertx
        .eventBus()
        .request(
            "poc.hello",
            "",
            reply -> {
              context.response().end((String) reply.result().body());
            });
  }

However, it doesn’t make sense to have so many handlers in my main verticle. I don’t assume this endpoint is going to be very fancy and have a lot of variables involved, but I want to be able to have a handler that can take all requests like /example/* to be handled in it’s respective exampleVerticle.

I could find any resources to do so but essentially this is how some pseudocode for what I want to be able to do.

// mainVerticle.java

start(){
  router.get("/example/*").handler(this::exampleHandler);
}

exampleHandler(){
  // routes to exampleVerticle
}
//exampleVerticle.java
start(){
  router.get("/example/hello").handler(this::helloExample);
}

void helloExample(RoutingContext context) {
  vertx
      .eventBus()
      .request(
          "example.hello",
          "",
          reply -> {
            // some sort of reply
          });
}

Obviously I don’t have much of an idea what I’m doing but I hope what I’m trying to do makes sense.

Thanks in advance!

New contributor

Vansh Sharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT