mqtt 测试
docker部署开源 mqtt broker 【eclipse-mosquitto】
bash
docker run -d \
--name mqtt \
-p 1883:1883 -p 9001:9001 -p 9883:9883 \
-v ./mqtt.conf:/mosquitto/config/mosquitto.conf \
eclipse-mosquitto
mqtt.conf 增加websocet监听
yaml
# This is a Mosquitto configuration file that creates a listener on port 1883
# that allows unauthenticated access.
listener 1883
allow_anonymous true
listener 9883
protocol http_api
http_dir /usr/share/mosquitto/dashboard
# WebSocket 监听
listener 9001
protocol websockets
vue中使用mqtt库
- 安装mqtt依赖
bash
npm install mqtt
注: vue3 bable.config.js 添加配置,否则启动报错
js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
// 新增plugins
plugins: [
'@babel/plugin-transform-private-methods'
]
}
- mqtt工具
js
import mqtt from 'mqtt'
// 9001 是 broker开放的websocket端口
const MQTT_URL = 'ws://localhost:9001/mqtt'
let client = null
/**
* 获取 MQTT 客户端(单例)
*/
export function getMqttClient(topic) {
if (!client) {
client = mqtt.connect(MQTT_URL, {
clientId: `vue2_${Math.random().toString(16).slice(2)}`,
clean: true,
reconnectPeriod: 4000,
connectTimeout: 5000
})
client.on('connect', () => {
console.log('[MQTT] connected')
client.subscribe(topic)
console.log('subscribe: ', topic)
})
client.on('error', err => {
console.error('[MQTT] error', err)
})
client.on('close', () => {
console.log('[MQTT] disconnected')
})
}
return client
}
java模拟设备上报数据
- 引用maven依赖
xml
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
- 上报数据
java
public static void main(String[] args) throws MqttException, InterruptedException {
String broker = "tcp://localhost:1883";
String clientId = "java-device-001";
String topic = "device/temp";
MqttClient client = new MqttClient(broker, clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
client.connect(options);
System.out.println("✅ Connected to MQTT Broker");
// 模拟温度上报
for (int i = 0; i < 50000; i++) {
String payload = "{\"temp\": " + (20 + i) + "}";
MqttMessage message = new MqttMessage(payload.getBytes());
message.setQos(1);
client.publish(topic, message);
System.out.println("📤 Published: " + payload);
Thread.sleep(2000);
}
client.disconnect();
client.close();
System.out.println("模拟数据上报关闭!!!");
}