Java
Use the Eclipse Paho Java client to connect Java 8+ applications and services to ConnectMQ over TLS.
How it connects
Install
xml
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>kotlin
implementation("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5")Publish and subscribe
java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.nio.charset.StandardCharsets;
public class Example {
static final String FILTER = "acme/istanbul/#";
static final String TOPIC = "acme/istanbul/assembly/line1/java-01/telemetry";
public static void main(String[] args) throws Exception {
String clientId = System.getenv("CMQ_CLIENT_ID") + "_java-service"; // issued client ID + "_" + suffix
MqttAsyncClient client = new MqttAsyncClient(
"ssl://broker.connectmq.com:8883", clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(System.getenv("CMQ_USERNAME"));
options.setPassword(System.getenv("CMQ_PASSWORD").toCharArray());
options.setKeepAliveInterval(60);
options.setCleanSession(true);
options.setAutomaticReconnect(true); // reconnect if the connection drops
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String serverUri) {
// Runs after the first connect and after every reconnect:
// a clean session has no subscriptions, so subscribe here
try {
client.subscribe(FILTER, 1);
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void messageArrived(String topic, MqttMessage message) {
System.out.println(topic + ": " + new String(message.getPayload(), StandardCharsets.UTF_8));
}
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost, reconnecting: " + cause.getMessage());
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) { }
});
client.connect(options).waitForCompletion();
while (true) {
if (client.isConnected()) {
byte[] payload = "{\"temperature\":21.5}".getBytes(StandardCharsets.UTF_8);
client.publish(TOPIC, payload, 1, false);
}
Thread.sleep(5000);
}
}
}bash
# Java 11+, with the Paho jar on the class path
CMQ_CLIENT_ID=connectmq_client_123456 CMQ_USERNAME=cmq_xxxx CMQ_PASSWORD='...' \
java -cp org.eclipse.paho.client.mqttv3-1.2.5.jar Example.javassl:// uses the JVM's trusted CAs to verify the broker certificate, so you do not need a keystore (Java 8u141 or later). The Paho v3 client speaks MQTT 3.1.1.
Use your issued client ID
MqttClient.generateClientId() creates a random ID that your private broker refuses with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per process (why).
Notes
connectCompleteruns after every reconnect. Subscribing there keeps subscriptions alive, because a clean session starts without any.- Use
MqttAsyncClientas above, orMqttClientfor simple scripts. Do not call blockingMqttClientmethods insidemessageArrived. - Send JSON objects such as
{"temperature": 21.5}: the console turns every numeric field into a live value with a sparkline. A JSON library such as Jackson or Gson can build the payload. - Try without an account: connect to
tcp://broker.connectmq.com:1883with no username or password. The public test broker is readable by anyone, so use it for experiments only.