Back
Close

Building a HTTP Endpoint with Eclipse Vert.x

cescoffier
9,055 views
Previous: Vert.x Next: Producing JSON

Create a HTTP server

Enough talking, time for action... First we need an instance of Vert.x. You can build one using Vertx.vertx():

Vert.x instance creation
package io.vertx.playground;
import io.vertx.core.Vertx;
public class VertxCreationExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
System.out.println("Vert.x instance: " + vertx);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Be aware that this method returns a new instance every time. So better store it if you need to reuse it.

Ok, now that we have our vertx instance, let's create a HTTP server. This is fairly easy:

Http Server Creation
package io.vertx.playground;
import io.vertx.core.Vertx;
public class HttpServerExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
vertx.createHttpServer()
.requestHandler(req -> {
req.response().end("hello !");
})
.listen(8080);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Let's look at the server creation. We attach a request handler. A Handler is a method taking as parameter an event (here the HTTP request) and reacting to it (here we write the message to the response). A Handler does not return a result, it provides its result in an asynchronous way. For instance, in our example, we write the HTTP response, sent asynchronously to the client by Vert.x.

The request handler is called for each incoming HTTP request. We start seeing emerging the reactive flavor of this application: for every request, we react.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants