Publishing and subscribing to MQTT Topics from a Micronaut Application
Learn how to use Mosquitto as an MQTT broker, create a Micronaut CLI application and publish an MQTT topic, and subscribe to the MQTT topic in a different Micronaut Messaging application.
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Test Resources
For this guide, we will use Mosquitto via Test Resources. As described in the MQTT section of the Test Resources documentation, configure a mosquitto container:
|
Note
|
This should be done in both apps for this guide. |
test-resources:
containers:
mosquitto:
image-name: eclipse-mosquitto
hostnames:
- mqtt.host
exposed-ports:
- mqtt.port: 1883
ro-fs-bind:
- "src/test-resources/mosquitto.conf": /mosquitto/config/mosquitto.confAnd then define the mosquitto configuration file:
persistence false
allow_anonymous true
connection_messages true
log_type all
listener 1883As we have defined that Test Resources are shared in the build, both applications will make use of the same instance of Mosquitto.
When running under production, you should replace this property with the location of your production message broker via an environment variable.
MQTT_CLIENT_SERVER_URI=tcp://production-server:1183Writing the CLI (Command Line Interface) Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-cli-app example.micronaut.micronautguide \
--features=mqtt,graalvm,awaitility \
--build=maven --lang=java|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
Rename this micronautguide directory to cli.
If you use Micronaut Launch, select Micronaut Application as application type and add mqtt, graalvm, and awaitility features.
|
Note
|
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
Create an MqttPublisher
Create an interface to publish MQTT topics:
Writing the CLI Command
Create an enum to allow the user to submit temperatures in Celsius or Fahrenheit:
package example.micronaut;
import io.micronaut.core.annotation.NonNull;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public enum Scale {
FAHRENHEIT("Fahrenheit"),
CELSIUS("Celsius");
private static final Map<String,Scale> ENUM_MAP;
private final String name;
Scale(String name) {
this.name = name;
}
static {
Map<String,Scale> map = new ConcurrentHashMap<>();
for (Scale instance : Scale.values()) {
map.put(instance.getName(), instance);
}
ENUM_MAP = Collections.unmodifiableMap(map);
}
@NonNull
public static Optional<Scale> of(@NonNull String name) {
return Optional.ofNullable(ENUM_MAP.get(name));
}
@NonNull
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
public static Set<String> candidates() {
return ENUM_MAP.keySet();
}
}Create a class to show completion candidates:
package example.micronaut;
import java.util.ArrayList;
public class TemperatureScaleCandidates extends ArrayList<String> {
public TemperatureScaleCandidates() {
super(Scale.candidates());
}
}Replace the command:
Replace the generated test with this:
The MQTT server URI is configured by referencing the properties that were set up for Mosquitto via Test Resources:
mqtt.client.server-uri=tcp://${mqtt.host}:${mqtt.port}
mqtt.client.client-id=${random.uuid}Writing an MQTT Subscriber Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-messaging-app example.micronaut.micronautguide \
--features=mqtt,graalvm,awaitility \
--build=maven --lang=java|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
Rename this micronautguide directory to app.
If you use Micronaut Launch, select Micronaut Application as application type and add mqtt, graalvm, and awaitility features.
|
Note
|
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
Configuration
The MQTT server URI is configured by referencing the properties that were set up for Mosquitto via Test Resources:
mqtt.client.server-uri=tcp://${mqtt.host}:${mqtt.port}
mqtt.client.client-id=${random.uuid}Create Subscriber
Add test
Running the Application
Run the Subscriber App
To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.
Keep it running. Once you publish a topic with the CLI application, you will see a log entry.
Run the CLI
Run the CLI command, which will publish a temperature at startup.
./gradlew run --args="-t 212 -s Fahrenheit"The subscriber receives the MQTT topic, as you will see in the logs:
12:09:47.280 [MQTT Call: 180d98b5-75b9-41be-a874-295289346592]
INFO e.micronaut.TemperatureListener - temperature: 100.00Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.
Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.
|
Note
|
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
GraalVM Installation
sdk install java 25.0.2-graalFor installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-imageThe native executable is created in the target directory and can be run with target/micronautguide.
It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:
Generate GraalVM native executables for both the CLI and the messaging application, then execute both. Publish a temperature, and you will see it in the subscriber logs.
Next Steps
Read more about Micronaut MQTT.
Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
License
|
Note
|
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |