Quarkus - Using Eclipse Vert.x

Eclipse Vert.x is a toolkit for building reactive applications.It is designed to be lightweight and embeddable.Vert.x defines a reactive execution model and provides a large ecosystem.Quarkus integrates Vert.x to implement different reactive features, such as asynchronous message passing, and non-blocking HTTP client.Basically, Quarkus uses Vert.x as its reactive engine.While lots of reactive features from Quarkus don’t show Vert.x, it’s used underneath.But you can also access the managed Vert.x instance and benefit from the Vert.x ecosystem.

Installing

To access Vert.x, well, you need to enable the vertx extension to use this feature.If you are creating a new project, set the extensions parameter are follows:

  1. mvn io.quarkus:quarkus-maven-plugin:1.0.0.CR1:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=vertx-quickstart \
  4. -Dextensions="vertx"
  5. cd vertx-quickstart

If you have an already created project, the vertx extension can be added to an existing Quarkus project withthe add-extension command:

  1. ./mvnw quarkus:add-extension -Dextensions="vertx"

Otherwise, you can manually add this to the dependencies section of your pom.xml file:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-vertx</artifactId>
  4. </dependency>

Accessing Vert.x

Once the extension has been added, you can access the managed Vert.x instance using @Inject:

  1. @Inject Vertx vertx;

If you are familiar with Vert.x, you know that Vert.x provides different API models.For instance bare Vert.x uses callbacks, the RX Java 2 version uses Single, Maybe, Completable, Observable and Flowable.

Quarkus provides 3 Vert.x APIs:

NameCodeDescription
bare@Inject io.vertx.core.Vertx vertxbare Vert.x instance, the API uses callbacks.
RX Java 2@Inject io.vertx.reactivex.core.Vertx vertxRX Java 2 Vert.x, the API uses RX Java 2 types.
Axle@Inject io.vertx.axle.core.Vertx vertxAxle Vert.x, the API uses CompletionStage and Reactive Streams.
You may inject any of the 3 flavors of Vertx as well as the EventBus in your Quarkus application beans: bare, Axle, RxJava2.They are just shims and rely on a single managed Vert.x instance.

You will pick one or the other depending on your use cases.

  • bare: for advanced usage or if you have existing Vert.x code you want to reuse in your Quarkus application

  • Axle: works well with Quarkus and MicroProfile APIs (CompletionStage for single results and Publisher for streams)

  • Rx Java 2: when you need support for a wide range of data transformation operators on your streams

The following snippets illustrate the difference between these 3 APIs:

  1. // Bare Vert.x:
  2. vertx.fileSystem().readFile("lorem-ipsum.txt", ar -> {
  3. if (ar.succeeded()) {
  4. System.out.println("Content:" + ar.result().toString("UTF-8"));
  5. } else {
  6. System.out.println("Cannot read the file: " + ar.cause().getMessage());
  7. }
  8. });
  9. // Rx Java 2 Vert.x
  10. vertx.fileSystem().rxReadFile("lorem-ipsum.txt")
  11. .map(buffer -> buffer.toString("UTF-8"))
  12. .subscribe(
  13. content -> System.out.println("Content: " + content),
  14. err -> System.out.println("Cannot read the file: " + err.getMessage())
  15. );
  16. // Axle API:
  17. vertx.fileSystem().readFile("lorem-ipsum.txt")
  18. .thenApply(buffer -> buffer.toString("UTF-8"))
  19. .whenComplete((content, err) -> {
  20. if (err != null) {
  21. System.out.println("Cannot read the file: " + err.getMessage());
  22. } else {
  23. System.out.println("Content: " + content);
  24. }
  25. });

Using Vert.x in Reactive JAX-RS resources

Quarkus web resources support asynchronous processing and streaming results over server-sent events.

Asynchronous processing

Most programming guides start easy with a greeting service and this one makes no exception.

To asynchronously greet a client, the endpoint method must return a java.util.concurrent.CompletionStage:

  1. @Path("/hello")
  2. public class GreetingResource {
  3. @Inject
  4. Vertx vertx;
  5. @GET
  6. @Produces(MediaType.TEXT_PLAIN)
  7. @Path("{name}")
  8. public CompletionStage<String> greeting(@PathParam String name) {
  9. // When complete, return the content to the client
  10. CompletableFuture<String> future = new CompletableFuture<>();
  11. long start = System.nanoTime();
  12. // TODO: asynchronous greeting
  13. return future;
  14. }
  15. }

So far so good.Now let’s use the Vert.x API to implement the artificially delayed reply with the setTimer provided by Vert.x:

  1. // Delay reply by 10ms
  2. vertx.setTimer(10, l -> {
  3. // Compute elapsed time in milliseconds
  4. long duration = MILLISECONDS.convert(System.nanoTime() - start, NANOSECONDS);
  5. // Format message
  6. String message = String.format("Hello %s! (%d ms)%n", name, duration);
  7. // Complete
  8. future.complete(message);
  9. });

That’s it.Now start Quarkus in dev mode with:

  1. ./mvnw compile quarkus:dev

Eventually, open your browser and navigate to http://localhost:8080/hello/Quarkus, you should see:

  1. Hello Quarkus! (10 ms)

Streaming using Server-Sent Events

Quarkus web resources that need to send content as server-sent events must have a method:

  • declaring the text/event-stream response content type

  • returning a Reactive Streams Publisher or an RX Java 2 Observable or Flowable

In practice, a streaming greeting service would look like:

  1. @Path("/hello")
  2. public class StreamingResource {
  3. @GET
  4. @Produces(MediaType.SERVER_SENT_EVENTS)
  5. @Path("{name}/streaming")
  6. public Publisher<String> greeting(@PathParam String name) {
  7. // TODO: create a Reactive Streams publisher
  8. return publisher;
  9. }
  10. }

How to create a Reactive Streams publisher?There are a few ways to do this:

  • If you use io.vertx.axle.core.Vertx, the API provides toPublisher methods (and then use RX Java 2 or Reactive Streams Operators to manipulate the stream)

  • You can also use io.vertx.reactivex.core.Vertx which already provides RX Java 2 (RX Java 2 Flowable implement Reactive Streams publisher).

The first approach can be implemented as follows:

  1. // Use io.vertx.axle.core.Vertx;
  2. @Inject Vertx vertx;
  3. @GET
  4. @Produces(MediaType.SERVER_SENT_EVENTS)
  5. @Path("{name}/streaming")
  6. public Publisher<String> greeting(@PathParam String name) {
  7. return vertx.periodicStream(2000).toPublisherBuilder()
  8. .map(l -> String.format("Hello %s! (%s)%n", name, new Date()))
  9. .buildRs();
  10. }

The second approach slightly differs:

  1. // Use io.vertx.reactivex.core.Vertx;
  2. @Inject Vertx vertx;
  3. @GET
  4. @Produces(MediaType.SERVER_SENT_EVENTS)
  5. @Path("{name}/streaming")
  6. public Publisher<String> greeting(@PathParam String name) {
  7. return vertx.periodicStream(2000).toFlowable()
  8. .map(l -> String.format("Hello %s! (%s)%n", name, new Date()));
  9. }

The server side is ready.In order to see the result in the browser, we need a web page.

META-INF/resources/streaming.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title>SSE with Vert.x - Quarkus</title>
  6. <script type="application/javascript" src="streaming.js"></script>
  7. </head>
  8. <body>
  9. <div id="container"></div>
  10. </body>
  11. </html>

Our web page just has an empty <div> container.The magic, as always, lies in the Javascript code:

META-INF/resources/streaming.js

  1. var eventSource = new EventSource("/hello/Quarkus/streaming");
  2. eventSource.onmessage = function (event) {
  3. var container = document.getElementById("container");
  4. var paragraph = document.createElement("p");
  5. paragraph.innerHTML = event.data;
  6. container.appendChild(paragraph);
  7. };
Most browsers support SSE but some don’t.More about this in Mozilla’s SSE browser-compatibility list.

Navigate to http://localhost:8080/streaming.html.A new greeting should show-up every 2 seconds.

  1. Hello Quarkus! (Thu Mar 21 17:26:12 CET 2019)
  2. Hello Quarkus! (Thu Mar 21 17:26:14 CET 2019)
  3. Hello Quarkus! (Thu Mar 21 17:26:16 CET 2019)
  4. ...

Using Vert.x JSON

Vert.x API heavily relies on JSON, namely the io.vertx.core.json.JsonObject and io.vertx.core.json.JsonArray types.They are both supported as Quarkus web resource request and response bodies.

Consider these endpoints:

  1. @Path("/hello")
  2. @Produces(MediaType.APPLICATION_JSON)
  3. public class VertxJsonResource {
  4. @GET
  5. @Path("{name}/object")
  6. public JsonObject jsonObject(@PathParam String name) {
  7. return new JsonObject().put("Hello", name);
  8. }
  9. @GET
  10. @Path("{name}/array")
  11. public JsonArray jsonArray(@PathParam String name) {
  12. return new JsonArray().add("Hello").add(name);
  13. }
  14. }

In your browser, navigate to http://localhost:8080/hello/Quarkus/object. You should see:

  1. {"Hello":"Quarkus"}

Then, navigate to http://localhost:8080/hello/Quarkus/array:

  1. ["Hello","Quarkus"]

Needless to say, this works equally well when the JSON content is a request body or is wrapped in a CompletionStage or Publisher.

Using Vert.x Clients

As you can inject a Vert.x instance, you can use Vert.x clients in a Quarkus application.This section gives an example with the WebClient.

Picking the right dependency

Depending on the API model you want to use you need to add the right dependency to your pom.xml file:

  1. <!-- bare API -->
  2. <dependency>
  3. <groupId>io.vertx</groupId>
  4. <artifactId>vertx-web-client</artifactId>
  5. </dependency>
  6. <!-- Axle API -->
  7. <dependency>
  8. <groupId>io.smallrye.reactive</groupId>
  9. <artifactId>smallrye-axle-web-client</artifactId>
  10. </dependency>
  11. <!-- RX Java 2 API -->
  12. <dependency>
  13. <groupId>io.vertx</groupId>
  14. <artifactId>vertx-rx-java2</artifactId>
  15. </dependency>
The vertx-rx-java2 provides the RX Java 2 API for the whole Vert.x stack, not only the web client.

In this guide, we are going to use the Axle API, so:

  1. <dependency>
  2. <groupId>io.smallrye.reactive</groupId>
  3. <artifactId>smallrye-axle-web-client</artifactId>
  4. </dependency>

Now, create a new resource in your project with the following content:

src/main/java/org/acme/vertx/ResourceUsingWebClient.java

  1. package org.acme.vertx;
  2. import io.vertx.axle.core.Vertx;
  3. import io.vertx.axle.ext.web.client.WebClient;
  4. import io.vertx.axle.ext.web.codec.BodyCodec;
  5. import io.vertx.core.json.JsonObject;
  6. import io.vertx.ext.web.client.WebClientOptions;
  7. import javax.annotation.PostConstruct;
  8. import javax.inject.Inject;
  9. import javax.ws.rs.GET;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.core.MediaType;
  13. import java.util.concurrent.CompletionStage;
  14. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  15. @Path("/swapi")
  16. public class ResourceUsingWebClient {
  17. @Inject
  18. Vertx vertx;
  19. private WebClient client;
  20. @PostConstruct
  21. void initialize() {
  22. this.client = WebClient.create(vertx,
  23. new WebClientOptions().setDefaultHost("swapi.co").setDefaultPort(443).setSsl(true));
  24. }
  25. @GET
  26. @Produces(MediaType.APPLICATION_JSON)
  27. @Path("/{id}")
  28. public CompletionStage<JsonObject> getStarWarsCharacter(@PathParam int id) {
  29. return client.get("/api/people/" + id)
  30. .send()
  31. .thenApply(resp -> {
  32. if (resp.statusCode() == 200) {
  33. return resp.bodyAsJsonObject();
  34. } else {
  35. return new JsonObject()
  36. .put("code", resp.statusCode())
  37. .put("message", resp.bodyAsString());
  38. }
  39. });
  40. }
  41. }

This resource creates a WebClient and upon request use this client to invoke the https://swapi.co/ API.Depending on the result the response is forwarded as it’s received, or a new JSON object is created with the status and body.The WebClient is obviously asynchronous (and non-blocking), to the endpoint returns a CompletionStage.

Run the application with:

  1. ./mvnw compile quarkus:dev

And then, open a browser to: http://localhost:8080/swapi/1. You should get Luke Skywalker.

The application can also run as a native executable.But, first, we need to instruct Quarkus to enable ssl.Open the src/main/resources/application.properties and add:

  1. quarkus.ssl.native=true

Then, create the native executable with:

  1. ./mvnw package -Pnative

Going further

There are many other facets of Quarkus using Vert.x underneath:

  • The event bus is the connecting tissue of Vert.x applications.Quarkus integrates it so different beans can interact with asynchronous messages.This part is covered in the Async Message Passing documentation.

  • Data streaming and Apache Kafka are a important parts of modern systems.Quarkus integrates data streaming using Reactive Messaging.More details on Interacting with Kafka.

  • Learn how to implement highly performant, low-overhead database applications on Quarkus with the Reactive SQL Clients.