Overview
In this article, we’ll talk about Vert.x, cover its center ideas and make a basic RESTfull web administration with it.
We’ll begin by covering the establishment ideas about the tool compartment. Gradually push ahead to a HTTP server and afterward assemble the RESTfull administration.

About Vert.x
Vert.x is an open source, responsive and bilingual programming advancement tool compartment from the engineers of Eclipse.
Receptive writing computer programs is a programming worldview and related with offbeat streams, which react to any progressions or occasions.
Vert.x also utilizes an occasion transport, to speak with various pieces of the application and passes occasions, nonconcurrently to controllers when they accessible.
We call it polyglot due to its support for multiple JVM and non-JVM languages like Java, Groovy, Ruby, Python, and JavaScript.
Setup Vert.x
To use Vert.x we need to add the Maven dependency:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>3.4.1</version>
</dependency>
Verticles
Verticles are bits of code that Vert.x motor executes. The tool compartment gives us many theoretical verticle class. It can be broadened and carried out as we need to being multilingual and verticles. and also it can be written in any of the upheld dialects. an application would commonly be made out of different verticles which are running in a similar Vert.x occurrence. And speak with one another utilizing occasions by means of the occasion bus.To make a verticle in JAVA, the class should carry out io.vertx.core.Verticle interface, or any of its subclasses.
Event Bus
It is the nerve arrangement of any Vert.x application.
Being responsive, verticles stay lethargic until they get a message or occasion. Verticles speak with one another through the occasion transport. The message can be anything from a string to a perplexing article.
Let’s create a simple application with a verticle and deploy it using a vertx instance.
To create our verticle, we’ll extend the io.vertx.core.AbstractVerticle class and override the start() method:
public class HelloVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { LOGGER.info("Welcome to Vertx"); } }
The start() method will be invoked by the vertx instance when the verticle is deployed and the method takes io.vertx.core.Future as a parameter, which can be used to discover the status of an asynchronous deployment of the verticle.
Now let’s deploy the verticle:
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new HelloVerticle());
}
Similarly we can override the stop() method from the AbstractVerticle class, after that it will be invoked while shutting down the verticle:
@Override
public void stop() {
LOGGER.info("Shutting down application");
}
HTTP Server
Now let’s spin up an HTTP server using a verticle:
@Override
public void start(Future<Void> future) {
vertx.createHttpServer()
.requestHandler(r -> r.response().end("Welcome to Vert.x Intro");
})
.listen(config().getInteger("http.port", 9090),
result -> {
if (result.succeeded()) {
future.complete();
} else {
future.fail(result.cause());
}
});
}
We have overridden the start() method to create an HTTP server and attached a request handler to it. The requestHandler() method is called every time whenever the server receives a request.
Finally, the server is bound to a port, and an AsyncResult<HttpServer> handler is passed to the listen() method whether or not the connection or the server startup is succeeded using future.complete() or future.fail() in the case of any errors.
Note that: config.getInteger() method is reading the value for HTTP port configuration. which is being loaded from an external conf.json file.
Let’s test our server:
@Test
public void whenReceivedResponse_thenSuccess(TestContext testContext) {
Async async = testContext.async();
vertx.createHttpClient()
.getNow(port, "localhost", "/", response -> {
response.handler(responseBody -> {
testContext.assertTrue(responseBody.toString().contains("Hello"));
async.complete();
});
});
}
For the test, let’s use vertx-unit along with JUnit.:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-unit</artifactId>
<version>3.4.1</version>
<scope>test</scope>
</dependency>
We can get the latest version here.
Here, Verticle is deployed in a vertx instance,in the setup() method of the unit test:
@Before
public void setup(TestContext testContext) {
vertx = Vertx.vertx();
vertx.deployVerticle(SimpleServerVerticle.class.getName(),
testContext.asyncAssertSuccess());
}
Similarly, We can say that the vertx instance is closed in the @AfterClass tearDown() method:
@After
public void tearDown(TestContext testContext) {
vertx.close(testContext.asyncAssertSuccess());
}
Notice that the @BeforeClass arrangement() technique takes a TestContext contention. This ups in controlling and testing the offbeat conduct of the test.
We have a second boundary to the deployVerticle() technique, testContext.asyncAssertSuccess(). On account of a disappointment, it bombs the test.
RESTful WebService in Vert.x
Firstly,we have created an HTTP server so now use that to host an RESTfull WebService in order do so we will need another Vert.x module called vertx-web and it will give a lot of additional features for web development on top of vertx-core.
Let’s add the dependency to our pom.xml:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>3.4.1</version>
</dependency>
We can find the latest version here.
Router and Routes
firstly let’s create a router for our WebService. This router will take a simple route of GET method, and handler method getArtilces():
Router router = Router.router(vertx);
router.get("/api/baeldung/articles/article/:id")
.handler(this::getArticles);
The getArticle() method is a simple method that returns new Article object:
private void getArticles(RoutingContext routingContext) {
String articleId = routingContext.request()
.getParam("id");
Article article = new Article(articleId,
"This is an intro to vertx", "baeldung", "01-02-2017", 1578);
routingContext.response()
.putHeader("content-type", "application/json")
.setStatusCode(200)
.end(Json.encodePrettily(article));
}
A Router, when gets a solicitation, searches for the matching course, and passes the solicitation further. The courses having a controller strategy related with it to do sumthing with the solicitation.
For our situation, the overseer summons the getArticle() strategy. It gets the routingContext object as a contention. Infers the way boundary id, and makes an Article object with it.
In the last piece of the technique, how about we conjure the reaction() strategy on the routingContext item and put the headers, set the HTTP reaction code, and end the reaction utilizing the JSON encoded article object.
Adding Router to Server
Now let’s add the router, created in the previous section to the HTTP server:
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", 8080),
result -> {
if (result.succeeded()) {
future.complete();
} else {
future.fail(result.cause());
}
});
Here ,we have added requestHandler(router::accept) to the server.When any request is received this instructs the server to invoke the accept() of the router object.
Now let’s test our WebService:
@Test public void givenId_whenReceivedArticle_thenSuccess(TestContext testContext) { Async async = testContext.async(); vertx.createHttpClient() .getNow(8080, "localhost", "/api/baeldung/articles/article/12345", response -> { response.handler(responseBody -> { testContext.assertTrue( responseBody.toString().contains("\"id\" : \"12345\"")); async.complete(); }); }); }
Packaging Vert.x Application
To package the application as a deployable Java Archive (.jar) now let’s use Maven Shade plugin and the configurations in the execution tag:
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>io.vertx.core.Starter</Main-Class>
<Main-Verticle>com.baeldung.SimpleServerVerticle</Main-Verticle>
</manifestEntries>
</transformer>
</transformers>
<artifactSet />
<outputFile>
${project.build.directory}/${project.artifactId}-${project.version}-app.jar
</outputFile>
</configuration>
In the manifestEntries, Main-Verticle indicates the starting point of the application and the Main-Class is a Vert.x class .Which creates the vertx instance and deploys the Main-Verticle.
Conclusion
In this initial article firstly we talked about the Vert.x tool compartment and its central ideas. Perceived how to make and HTTP server, with Vert.x and furthermore a RESTFull WebService and told the best way to test them utilizing vertx-unit.
Finally packaged the application as an executable jar.
The complete implementation of the code snippets is available over on GitHub.
