Building a HTTP Endpoint with Eclipse Vert.x

cescoffier
3,328 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
1
2
3
4
5
6
7
8
9
10
11
12
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content