Build Real‑Time Chat with RabbitMQ MQTT in SpringBoot and Pure Front‑End
This guide explains how to use the lightweight MQTT protocol with RabbitMQ, covering Docker setup, enabling the MQTT plugin, testing with MQTTX, creating a front‑end chat using MQTT.js, and integrating MQTT into a SpringBoot application for server‑side messaging, all without writing custom back‑end code.
MQTT Protocol
MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol built on TCP/IP, offering real‑time reliable communication with minimal code and bandwidth.
Related Concepts
Publisher – the sender of messages.
Subscriber – the receiver of messages.
Broker – the intermediary between publishers and subscribers.
Topic – the routing key for messages.
Payload – the message content.
QoS – Quality of Service with three levels: QoS 0 (at most once), QoS 1 (at least once), QoS 2 (exactly once).
Enable MQTT in RabbitMQ
RabbitMQ does not enable MQTT by default; it must be turned on manually.
Run RabbitMQ with Docker:
docker run -p 5672:5672 -p 15672:15672 -p 1883:1883 -p 15675:15675 --name rabbitmq-mqtt \
-v /mydata/rabbitmq-mqtt/data:/var/lib/rabbitmq \
-d rabbitmq:3.9.11-managementEnter the container and enable the MQTT Web plugin:
# Enter the container
docker exec -it rabbitmq-mqtt /bin/bash
# Enable the plugin (also enables rabbitmq_mqtt)
rabbitmq-plugins enable rabbitmq_web_mqttAfter enabling, the MQTT Web service listens on port 15675.
MQTT Client (MQTTX)
Use MQTTX to test the instant‑messaging functionality.
Run MQTTX in Docker:
docker run -p 80:80 --name mqttx-web -d emqx/mqttx-webOpen http://192.168.3.101, add a connection, select MQTT 3.1.1, create a subscription (e.g., testTopicA), and send messages.
Front‑End Direct Instant Messaging
HTML + JavaScript can implement a simple chat without any back‑end code.
Use the MQTT.js library (https://github.com/mqttjs/MQTT.js) to connect to ws://192.168.3.101:15675/ws.
HTML page provides inputs for target topic and message, and buttons to send or clear messages.
<!-- simplified HTML example -->
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Chat</title></head>
<body>
<div>
<label>Target Topic: <input id="targetTopicInput" type="text"></label><br/>
<label>Message: <input id="messageInput" type="text"></label><br/>
<button onclick="sendMessage()">Send</button>
<button onclick="clearMessage()">Clear</button>
<div id="messageDiv"></div>
</div>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
const url = 'ws://192.168.3.101:15675/ws';
const topic = getQueryString("topic");
const client = mqtt.connect(url);
client.on('connect', () => client.subscribe(topic));
client.on('message', (t, m) => showMessage('Received: ' + m.toString()));
function sendMessage() {
const t = document.getElementById('targetTopicInput').value;
const m = document.getElementById('messageInput').value;
client.publish(t, m);
showMessage('Sent to ' + t + ': ' + m);
}
function showMessage(msg) {
const div = document.getElementById('messageDiv');
const el = document.createElement('div');
el.innerText = msg;
div.appendChild(el);
}
function clearMessage() { document.getElementById('messageDiv').innerHTML = ''; }
function getQueryString(name) {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const r = window.location.search.substr(1).match(reg);
return r ? decodeURIComponent(r[2]) : null;
}
</script>
</body>
</html>Integrate MQTT in SpringBoot
When the front‑end needs to be notified by the server, integrate MQTT into a SpringBoot application.
Add spring-integration-mqtt dependency in pom.xml.
Configure connection properties in application.yml (url, username, password, defaultTopic).
Create a configuration class ( MqttConfig) to bind these properties.
Define inbound channel, adapter, and a @ServiceActivator to handle incoming messages.
Define outbound channel, client factory, and a @ServiceActivator to publish messages.
Declare a @MessagingGateway ( MqttGateway) with methods to send to the default topic, a specific topic, or a topic with custom QoS.
Expose a REST controller ( MqttController) with endpoints /sendToDefaultTopic and /sendToTopic that delegate to MqttGateway.
// pom.xml snippet
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
// application.yml snippet
rabbitmq:
mqtt:
url: tcp://192.168.3.101:1883
username: guest
password: guest
defaultTopic: testTopic
// MqttConfig.java (fields: username, password, defaultTopic, url)
// MqttInboundConfig.java (defines mqttInputChannel, inbound adapter, handler)
// MqttOutboundConfig.java (defines client factory, outbound channel, handler)
// MqttGateway.java (interface with sendToMqtt methods)
// MqttController.java (REST endpoints)Conclusion
Message middleware such as RabbitMQ with MQTT support enables reliable asynchronous communication and real‑time instant messaging. For simple scenarios, a front‑end client can connect directly via MQTT; for more complex requirements, SpringBoot integration provides a robust server‑side solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
