dp-mq-client
v1.0.5
Published
javascript typescript ioc node.js
Downloads
5
Readme
dp-mq-client
。 简单易用的mqtt 客户端 库。
一、安装
- npm i dp-ioc
二、快速开始
import { MqttClient, connect } from "mqtt";
import { DpMqClient, MqMessage } from "dp-mq-client"
//定义一个消息体
@MqMessage({
topic: "a/b/c", // 消息主题
})
class TestMsg {
constructor(
public name: string,
public age: number
) { }
}
// 初始化客户端
let mqttClient = connect("mqtt://127.0.0.1", { port: 10084, password: "xx", username: "xxx" });
mqttClient.on("connect", () => {
let dpMq = new DpMqClient();
dpMq.init(mqttClient);
// 实例化消息体
let testMsg = new TestMsg("rajan", 18);
// 订阅消息
dpMq.subscribe<TestMsg>(testMsg, (msg) => {
// 当有消息时触发回调。
})
// 发布消息
dpMq.publish(testMsg);
// 取消订阅消息
dpMq.unsubscribe(testMsg);
})
注意,取消订阅时,需要传入消息体实例而非类
如果使用在dp-uni-api-framework 框架下,可以如此引入:
...
class App {
@Inject(DpMqClient)
dpMqClient:DpMqClient;
@BeforeBoot
async beforeBoot(){
// callback写法
let mqttClient = connect("mqtt://127.0.0.1", { port: 10084, password: "xx", username: "xxx" });
mqttClient.on("connect", () => {
this.dpMqClient.init(mqttClient);
})
// 或者使用await写法 [推荐]
await new Promise((resolve,reject)=>{
let mqttClient = connect("mqtt://127.0.0.1", { port: 10084, password: "xx", username: "xxx" });
mqttClient.on("connect", () => {
this.dpMqClient.init(mqttClient);
resolve();
})
mqttClient.on("error", () => {
reject();
})
})
}
}
...
三、高级用法
3.1 订阅消息时, 同一个消息体类多个实例对象,每个实例对象的消息回调是独立的。
@MqMessage({
topic: "a/b/c",
})
class TestMsg {
constructor(
public name: string,
public age: number
) { }
}
//定义两个消息实例
let testMsg1 = new TestMsg("rajan1", 19);
let testMsg2 = new TestMsg("rajan2", 20);
// 订阅消息
dpMq.subscribe<TestMsg>(testMsg1, (msg) => {
// 消息回调1
})
// 订阅消息
dpMq.subscribe<TestMsg>(testMsg2, (msg) => {
// 消息回调2
})
当然,取消订阅(unsubscribe)也是独立的。
3.2 动态更新 meta 元信息
import { metaUpdate,MqMessage } from "dp-mq-client"
@MqMessage({
topic: "a/b/c",
})
class TestMsg {
constructor(
public name: string,
public age: number
) { }
}
let testMsg1 = new TestMsg("rajan1", 19);
metaUpdate(testMsg1,{ topic: "a/c/c"});// 更新testMsg1对象的元信息
四、支持
如果在使用过程中,遇到问题,请到git仓库反馈 仓库地址