Skip to main content

Introducing Vert.x MQTT client

In this article we will see how to sett up the new Vert.x MQTT client. Actually, I have a real example so you can try it quickly.

If you are using Maven or Gradle, add the following dependency to the dependencies section of your project descriptor to access the Vert.x MQTT client:

  • Maven (in your pom.xml):
  • Gradle (in your build.gradle file):
dependencies {
  compile 'io.vertx:vertx-mqtt:3.5.0.Beta1'

Now that you’ve set up your project, you can create a simple application which will receive all messages from all broker channels:

import io.vertx.core.AbstractVerticle;
import io.vertx.mqtt.MqttClient;
import io.vertx.mqtt.MqttClientOptions;


public class MainVerticle extends AbstractVerticle {

  public void start() {
     MqttClientOptions options = new MqttClientOptions();
      // specify broker host
      // specify max size of message in bytes

    MqttClient client = MqttClient.create(vertx, options);

    client.publishHandler(s -> {
      try {
        String message = new String(s.payload().getBytes(), "UTF-8");
        System.out.println(String.format("Receive message with content: \"%s\" from topic \"%s\"", message, s.topicName()));
      } catch (UnsupportedEncodingException e) {

    client.connect(s -> {
      // subscribe to all subtopics
      client.subscribe("#", 0);

The publishHandler is the handler called each time the broker, located at, sends a message to you, from the topics you are subscribing for.

But only providing a handler is not enough, you should also connect to the broker and subscribe to some topics. For this reason, you should use the connect method and then call subscribe when the connection established.

To deploy this verticle from an application you should have in your main method something like that:

Vertx vertx = Vertx.vertx();

When you have completed all steps correctly the result should look like that:

As the alternative and recommended way to bootstrap Vert.x applications you can use vertx-maven-starter or vertx-gradle-starter. For completing this guide I have used the first one. The final source code available here. If you would like to learn more about Vert.x MQTT client API then check out the full documentation and more examples.

Thank you for reading!