javascript - mqtt async 等待并发消息然后响应相应的 http post 请求
问题描述
我有这个家庭自动化项目的过程。
- 在我的服务器的 HTTP 请求中接收消息。
- 将上述步骤中的消息通过 MQTT 主题发布到设备。
- 等待 5 秒以通过 MQTT 主题接收设备的响应。
- 如果在 5 秒内收到响应,则发送成功响应,否则发送错误响应,到步骤 1 中的原始 HTTP 请求
下面是取自另一个问题的代码,因为它与我正在尝试做的事情完全匹配。
此代码一次只能处理一个请求。我应该怎么做来处理并发请求?
var resp;
var timeOutValue = 5000; //wait 5 seconds
var timer;
const client = mqtt.connect(MQTTServer)
client.on('message', (topic, message) => {
resp.send(message);
client.unsubscribe('inTopic');
resp = undefined;
clearTimeout(timer)
}
app.post('/test', function (request, response) {
resp = response;
client.publish ('outTopic' , 'request ');
client.subscribe('inTopic');
timer = setTimeout(function(){
if (resp) {
resp.send(message);
resp = undefined;
client.unsubscribe('inTopic');
}
}, timeOutValue);
}
我试过这个:
- 我将 HTTP 请求正文存储在数据库中,并在 MQTT 请求中向设备发送与存储记录相对应的唯一 ID。
- 这个唯一的 id 作为响应从设备发回。
- 当通过 MQTT 接收到任何消息时,我会检查数据库中是否存在唯一 ID,如果存在则检索记录并根据记录中存在的请求正文发送响应。
- 我等待 5 秒从设备获得响应,否则我会向 HTTP 发送错误响应。
但我不知道它是否适用于并发请求,因为我是 nodejs 的新手。所有这些都发生在 http post 路由处理程序中。
解决方案
export async function scheduleMqtt() {
var topic= 'office/csb_1';
var topic1=topic;
console.log("MQTT is started")
var client = mqtt.connect(mqtturl, options);
client.on('connect', mqtt_connect);
function mqtt_connect() {
console.log('client has connected successfully');
client.subscribe(topic, 0, mqtt_subscribe);
client.on('message', mqtt_messsageReceived);
console.log(topic);
};
function mqtt_subscribe(err, granted) {
console.log("Subscribed to " + topic);
if (err) { console.log(err); }
console.log("Granted:")
console.log(granted)
client.publish(topic);
console.log("topic");
client.on('message', function (topic, message) {
console.log(message.toString()); //if toString is not given, the message comes as buffer
});
};
推荐阅读
- java - 带有 @ManyToMany 字段的 Spring Data DTO 投影
- ios - 如何在 Swift 中使用领域过滤数据类型
- javascript - 我可以使用 node.js 监控现有的串行端口通信吗?
- angular - Angular/RxJS 6 - 如何对由 next() 触发的指令进行单元测试引发异常
- python - urllib2 多次读取响应
- javascript - 使用 Symbol.for 改变原生原型
- c# - 计算更新错误运算符中的百分比相乘
- java - 如何使用 Selenium WD + Java + JUnit 通过 js-doc-upload 按钮上传文件?
- python-3.x - 如何将 sympy 符号图与基于数据的散点图/线图结合起来?
- javascript - Ng Recaptcha - 在 Angular NgModule 中为提供者中的 userValue 动态加载值