Red Hat
Aug 20, 2017
by Vert.x community member

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):
<dependency>
    <groupId>io.vertxgroupId>
    <artifactId>vertx-mqttartifactId>
    <version>3.5.0.Beta1version>
dependency>
  • 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;

import java.io.UnsupportedEncodingException;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start() {
     MqttClientOptions options = new MqttClientOptions();
      // specify broker host
      options.setHost("iot.eclipse.org");
      // specify max size of message in bytes
      options.setMaxMessageSize(100_000_000);

    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) {
        e.printStackTrace();
      }
    });

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

The publishHandler is the handler called each time the broker, located at iot.eclipse.org:1883, 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();
vertx.deployVerticle(MainVerticle.class.getCanonicalName());

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!

Cheers!

Original Post