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 is based on Vert.x, and almost all network-related features rely on Vert.x. While lots of reactive features from Quarkus don’t show Vert.x, it’s used underneath. Quarkus also integrates smoothly with the Vert.x event bus (to enable asynchronous messaging passing between application components) and some reactive clients. You can also use various Vert.x APIs in your Quarkus application, such as deploying verticles, instantiating clients…​

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.7.6.Final: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 with the 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>

Native Transport

Vert.x is capable of using Netty’s native transports which offers performance improvements on certain platforms. To enable them you must include the appropriate dependency for your platform. It’s usually a good idea to include both to keep your application platform agnostic. Netty is smart enough to use the correct one, that includes none at all on unsupported platforms:

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-transport-native-epoll</artifactId>
  4. <classifier>linux-x86_64</classifier>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.netty</groupId>
  8. <artifactId>netty-transport-native-kqueue</artifactId>
  9. <classifier>osx-x86_64</classifier>
  10. </dependency>

You will also have to explicitly configure Vert.x to use the native transport. In application.properties add:

  1. quarkus.vertx.prefer-native-transport=true

Or in application.yml:

  1. quarkus:
  2. vertx:
  3. prefer-native-transport: true

If all is well quarkus will log:

  1. [io.qua.ver.cor.run.VertxCoreRecorder] (main) Vertx has Native Transport Enabled: true

Native Linux Transport

On Linux you can enable the following socket options:

  • SO_REUSEPORT
  1. quarkus.http.so-reuse-port=true
  • TCP_QUICKACK
  1. quarkus.http.tcp-quick-ack=true
  • TCP_CORK
  1. quarkus.http.tcp-cork=true
  • TCP_FASTOPEN
  1. quarkus.http.tcp-fast-open=true

Native MacOS Transport

On MacOS Sierra and above you can enable the following socket options:

  • SO_REUSEPORT
  1. quarkus.http.so-reuse-port=true

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 Mutiny variants uses Uni and Multi, the RX Java 2 version uses Single, Maybe, Completable, Observable and Flowable…​

Quarkus provides 4 Vert.x APIs:

NameCodeDescription

bare

@Inject io.vertx.core.Vertx vertx

bare Vert.x instance, the API uses callbacks.

Mutiny

@Inject io.vertx.mutiny.core.Vertx vertx

The Mutiny API for Vert.x.

RX Java 2

@Inject io.vertx.reactivex.core.Vertx vertx

RX Java 2 Vert.x, the API uses RX Java 2 types (deprecated).

Axle

@Inject io.vertx.axle.core.Vertx vertx

Axle Vert.x, the API uses CompletionStage and Reactive Streams (deprecated).

You may inject any of the 4 flavors of Vertx as well as the EventBus in your Quarkus application beans: bare, Mutiny, 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

  • mutiny: Mutiny is an event-driven reactive programming API. It uses 2 types: Uni and Multi. This is the recommended API.

  • Axle: works well with Quarkus and MicroProfile APIs (CompletionStage for single results and Publisher for streams) - deprecated, it is recommended to switch to Mutiny

  • Rx Java 2: when you need support for a wide range of data transformation operators on your streams - deprecated, it is recommended to switch to Mutiny

The following snippets illustrate the difference between these 4 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. // Mutiny Vert.x:
  10. vertx.fileSystem().readFile("lorem-ipsum.txt")
  11. .onItem().transform(buffer -> buffer.toString("UTF-8"))
  12. .subscribe()
  13. .with(
  14. content -> System.out.println("Content: " + content),
  15. err -> System.out.println("Cannot read the file: " + err.getMessage())
  16. );
  17. // Rx Java 2 Vert.x
  18. vertx.fileSystem().rxReadFile("lorem-ipsum.txt")
  19. .map(buffer -> buffer.toString("UTF-8"))
  20. .subscribe(
  21. content -> System.out.println("Content: " + content),
  22. err -> System.out.println("Cannot read the file: " + err.getMessage())
  23. );
  24. // Axle API:
  25. vertx.fileSystem().readFile("lorem-ipsum.txt")
  26. .thenApply(buffer -> buffer.toString("UTF-8"))
  27. .whenComplete((content, err) -> {
  28. if (err != null) {
  29. System.out.println("Cannot read the file: " + err.getMessage());
  30. } else {
  31. System.out.println("Content: " + content);
  32. }
  33. });
Mutiny

If you’re not familiar with Mutiny, we recommend to read the Getting Started with Reactive guide first.

Using Vert.x in Reactive JAX-RS resources

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

Asynchronous processing

To asynchronously handle the HTTP request, the endpoint method must return a java.util.concurrent.CompletionStage or an io.smallrye.mutiny.Uni (requires the quarkus-resteasy-mutiny extension):

  1. @Path("/lorem")
  2. public class GreetingResource {
  3. @GET
  4. @Produces(MediaType.TEXT_PLAIN)
  5. public Uni<String> doSomethingAsync() {
  6. // Mimic an asynchronous computation.
  7. return Uni.createFrom()
  8. .item(() -> "Hello!")
  9. .onItem().delayIt().by(Duration.ofMillis(10));
  10. }
  11. }
  1. ./mvnw compile quarkus:dev

Then, open your browser to http://localhost:8080/lorem and you should get the message.

So far so good. Now let’s use the Vert.x API instead of this artificial delay:

  1. package org.acme.vertx;
  2. import io.smallrye.mutiny.Uni;
  3. import io.vertx.mutiny.core.Vertx;
  4. import javax.inject.Inject;
  5. import javax.ws.rs.GET;
  6. import javax.ws.rs.Path;
  7. import javax.ws.rs.Produces;
  8. import javax.ws.rs.core.MediaType;
  9. @Path("/lorem")
  10. public class GreetingResource {
  11. @Inject
  12. Vertx vertx;
  13. @GET
  14. @Produces(MediaType.TEXT_PLAIN)
  15. public Uni<String> doSomethingAsync() {
  16. return vertx.fileSystem().readFile("/META-INF/resources/lorem.txt")
  17. .onItem().transform(b -> b.toString("UTF-8"));
  18. }
  19. }

In this code, we inject the vertx instance (io.vertx.mutiny.core.Vertx) and read a file from the file system.

Create the src/main/resources/META_INF/resources/lorem.txt file with the following content:

  1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Then, refresh the page, you should see the lorem ipsum text.

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 Mutiny Multi (requires the quarkus-resteasy-mutiny extension)

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}")
  6. public Multi<String> greeting(@PathParam String name) {
  7. // TODO: create a Reactive Streams publisher or a Mutiny Multi
  8. return publisher;
  9. }
  10. }

Now we just need to return our Publisher or Multi:

  1. package org.acme.vertx;
  2. import io.smallrye.mutiny.Multi;
  3. import io.vertx.mutiny.core.Vertx;
  4. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  5. import javax.inject.Inject;
  6. import javax.ws.rs.GET;
  7. import javax.ws.rs.Path;
  8. import javax.ws.rs.Produces;
  9. import javax.ws.rs.core.MediaType;
  10. import java.util.Date;
  11. @Path("/stream")
  12. public class StreamingResource {
  13. @Inject
  14. Vertx vertx;
  15. @GET
  16. @Produces(MediaType.SERVER_SENT_EVENTS)
  17. @Path("/{name}")
  18. public Multi<String> greeting(@PathParam String name) {
  19. return vertx.periodicStream(2000).toMulti()
  20. .map(l -> String.format("Hello %s! (%s)%n", name, new Date()));
  21. }
  22. }

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. if (!!window.EventSource) {
  2. var eventSource = new EventSource("/stream/Quarkus");
  3. eventSource.onmessage = function (event) {
  4. var container = document.getElementById("container");
  5. var paragraph = document.createElement("p");
  6. paragraph.innerHTML = event.data;
  7. container.appendChild(paragraph);
  8. };
  9. } else {
  10. window.alert("EventSource not available on this browser.")
  11. }
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! (Wed Feb 12 17:13:55 CET 2020)
  2. Hello Quarkus! (Wed Feb 12 17:13:57 CET 2020)
  3. Hello Quarkus! (Wed Feb 12 17:13:59 CET 2020)
  4. Hello Quarkus! (Wed Feb 12 17:14:01 CET 2020)
  5. Hello Quarkus! (Wed Feb 12 17:14:03 CET 2020)
  6. ...

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 Uni, Multi, 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. <!-- Mutiny API -->
  7. <dependency>
  8. <groupId>io.smallrye.reactive</groupId>
  9. <artifactId>smallrye-mutiny-vertx-web-client</artifactId>
  10. </dependency>
  11. <!-- Axle API -->
  12. <dependency>
  13. <groupId>io.smallrye.reactive</groupId>
  14. <artifactId>smallrye-axle-web-client</artifactId>
  15. </dependency>
  16. <!-- RX Java 2 API -->
  17. <dependency>
  18. <groupId>io.vertx</groupId>
  19. <artifactId>vertx-rx-java2</artifactId>
  20. </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 Mutiny API, so:

  1. <dependency>
  2. <groupId>io.smallrye.reactive</groupId>
  3. <artifactId>smallrye-mutiny-vertx-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 javax.annotation.PostConstruct;
  3. import javax.inject.Inject;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import javax.ws.rs.core.MediaType;
  8. import io.smallrye.mutiny.Uni;
  9. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  10. import io.vertx.mutiny.core.Vertx;
  11. import io.vertx.mutiny.ext.web.client.WebClient;
  12. import io.vertx.core.json.JsonObject;
  13. import io.vertx.ext.web.client.WebClientOptions;
  14. @Path("/fruit-data")
  15. public class ResourceUsingWebClient {
  16. @Inject
  17. Vertx vertx;
  18. private WebClient client;
  19. @PostConstruct
  20. void initialize() {
  21. this.client = WebClient.create(vertx,
  22. new WebClientOptions().setDefaultHost("fruityvice.com")
  23. .setDefaultPort(443).setSsl(true).setTrustAll(true));
  24. }
  25. @GET
  26. @Produces(MediaType.APPLICATION_JSON)
  27. @Path("/{name}")
  28. public Uni<JsonObject> getFruitData(@PathParam("name") String name) {
  29. return client.get("/api/fruit/" + name)
  30. .send()
  31. .onItem().transform(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 fruityvice 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 Uni.

Run the application with:

  1. ./mvnw compile quarkus:dev

And then, open a browser to: [http://localhost:8080/fruit-data/pear](http://localhost:8080/fruit-data/pear). You should get some details about pears.

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

Deploying verticles

Verticles is “a simple, scalable, actor-like deployment and concurrency model” provided by _Vert.x_. This model does not claim to be a strict actor-model implementation, but it does share similarities especially with respect to concurrency, scaling and deployment. To use this model, you write and deploy verticles, communicating with each other by sending messages on the event bus.

You can deploy verticles in Quarkus. It supports:

  • bare verticle - Java classes extending io.vertx.core.AbstractVerticle

  • Mutiny verticle - Java classes extending io.smallrye.mutiny.vertx.core.AbstractVerticle

To deploy verticles, use the regular Vert.x API:

  1. @Inject Vertx vertx;
  2. // ...
  3. vertx.deployVerticle(MyVerticle.class.getName(), ar -> { });
  4. vertx.deployVerticle(new MyVerticle(), ar -> { });

You can also pass deployment options to configure the verticle as well as set the number of instances.

Verticles are not beans by default. However, you can implement them as ApplicationScoped beans and get injection support:

  1. package io.quarkus.vertx.verticles;
  2. import io.smallrye.mutiny.Uni;
  3. import io.smallrye.mutiny.vertx.core.AbstractVerticle;
  4. import org.eclipse.microprofile.config.inject.ConfigProperty;
  5. import javax.enterprise.context.ApplicationScoped;
  6. @ApplicationScoped
  7. public class MyBeanVerticle extends AbstractVerticle {
  8. @ConfigProperty(name = "address") String address;
  9. @Override
  10. public Uni<Void> asyncStart() {
  11. return vertx.eventBus().consumer(address)
  12. .handler(m -> m.replyAndForget("hello"))
  13. .completionHandler();
  14. }
  15. }

You don’t have to inject the vertx instance but instead leverage the instance stored in the protected field of AbstractVerticle.

Then, deploy the verticle instance with:

  1. package io.quarkus.vertx.verticles;
  2. import io.quarkus.runtime.StartupEvent;
  3. import io.vertx.mutiny.core.Vertx;
  4. import javax.enterprise.context.ApplicationScoped;
  5. import javax.enterprise.event.Observes;
  6. @ApplicationScoped
  7. public class VerticleDeployer {
  8. public void init(@Observes StartupEvent e, Vertx vertx, MyBeanVerticle verticle) {
  9. vertx.deployVerticle(verticle).await().indefinitely();
  10. }
  11. }

If you want to deploy every exposed AbstractVerticle, you can use:

  1. public void init(@Observes StartupEvent e, Vertx vertx, Instance<AbstractVerticle> verticles) {
  2. for (AbstractVerticle verticle : verticles) {
  3. vertx.deployVerticle(verticle).await().indefinitely();
  4. }
  5. }

Listening to a Unix Domain Socket

Listening on a unix domain socket allows us to dispense with the overhead of TCP if the connection to the quarkus service is established from the same host. This can happen if access to the service goes through a proxy which is often the case if you’re setting up a service mesh with a proxy like Envoy.

This will only work on platforms that support Native Transport.

To setup please enable the appropriate Native Transport and set the following environment property:

  1. quarkus.http.domain-socket=/var/run/io.quarkus.app.socket
  2. quarkus.http.domain-socket-enabled=true

By itself this will not disable the tcp socket which by default will open on 0.0.0.0:8080. It can be explicitly disabled:

  1. quarkus.http.host-enabled=false

These properties can be set through Java’s -D command line parameter or on application.properties.

Read only deployment environments

In environments with read only file systems you may receive errors of the form:

  1. java.lang.IllegalStateException: Failed to create cache dir

Assuming /tmp/ is writeable this can be fixed by setting the vertx.cacheDirBase property to point to a directory in /tmp/ for instance in OpenShift by creating an environment variable JAVA_OPTS with the value -Dvertx.cacheDirBase=/tmp/vertx.

Running behind a reverse proxy

Quarkus could be accessed through proxies that additionally generate headers (e.g. X-Forwarded-Host) to keep information from the client-facing side of the proxy servers that is altered or lost when they are involved. In those scenarios, Quarkus can be configured to automatically update information like protocol, host, port and URI reflecting the values in these headers.

Activating this feature makes the server exposed to several security issues (i.e. information spoofing). Consider activate it only when running behind a reverse proxy.

To setup this feature, please include the following lines in src/main/resources/application.properties:

  1. quarkus.http.proxy-address-forwarding=true

To consider only de-facto standard header (Forwarded header), please include the following lines in src/main/resources/application.properties:

  1. quarkus.http.allow-forwarded=true

To consider only non-standard headers, please include the following lines instead in src/main/resources/application.properties:

  1. quarkus.http.proxy-address-forwarding=true
  2. quarkus.http.proxy.enable-forwarded-host=true
  3. quarkus.http.proxy.enable-forwarded-prefix=true

Both configurations related with standard and non-standard headers can be combine. In this case, the Forwarded header will have precedence in presence of both set of headers.

Supported forwarding address headers are:

  • Forwarded

  • X-Forwarded-Proto

  • X-Forwarded-Host

  • X-Forwarded-Port

  • X-Forwarded-Ssl

  • X-Forwarded-Prefix

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 event bus 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.