DEV Community

smolthing
smolthing

Posted on

Build web application in Vert.x [Part 1/ ♾️]

TL;DR: Start a simple vert.x web application with health check.

Steps

  1. Download Vertx Starter.zip: Java, Gradle and everything nice. Or you can use my exquisite buffet selection below:
curl -G https://start.vertx.io/starter.zip -d "groupId=com.example" -d "artifactId=starter" -d "vertxVersion=4.4.4" -d "vertxDependencies=vertx-web,vertx-web-client,vertx-web-graphql,vertx-web-sstore-redis,vertx-web-sstore-cookie,vertx-web-validation,vertx-web-openapi,vertx-service-discovery,vertx-circuit-breaker,vertx-config,vertx-kafka-client,vertx-consul-client,vertx-tcp-eventbus-bridge,vertx-micrometer-metrics,vertx-health-check,vertx-junit5,vertx-zookeeper,vertx-grpc-server,vertx-grpc-client,vertx-service-proxy,vertx-grpc-context-storage,vertx-http-service-factory,vertx-json-schema,vertx-shell" -d "language=java" -d "jdkVersion=11" -d "buildTool=gradle" --output starter.zip
Enter fullscreen mode Exit fullscreen mode
  1. Run command: ./gradlew run ./gradlew run
  2. Go to http://localhost:8888 localhost saying hello
  3. Add a router and health check using Using Vert.x Health Checks a. Add
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.healthchecks.HealthCheckHandler;
import io.vertx.ext.healthchecks.HealthChecks;
import io.vertx.ext.web.Router;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    HealthCheckHandler healthCheckHandler = HealthCheckHandler
      .createWithHealthChecks(HealthChecks.create(vertx));
    HealthCheckManager.configureHealthChecks(healthCheckHandler);

    Router router = Router.router(vertx);
    router.get("/ping").handler(healthCheckHandler);
    router.get("/*").handler(routingContext -> {
      routingContext.response()
        .putHeader("content-type", "text/plain; charset=utf-8")
        .end("Hello smolthing \uD83D\uDCA9.");
    });

    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server is running on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
Enter fullscreen mode Exit fullscreen mode
import io.vertx.ext.healthchecks.HealthCheckHandler;
import io.vertx.ext.healthchecks.Status;

public class HealthCheckManager {
  public static void configureHealthChecks(HealthCheckHandler healthCheckHandler) {
    healthCheckHandler.register("App connection", promise -> {
      promise.complete(Status.OK());
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

healthcheck

Add catch all regex to say Hello smolthing 💩

Reference

Top comments (0)