我使用 AWS Lambda 函数将 MQTT 消息发布到 AWS 外部托管的 Mosquitto Broker。
我使用的是 Node mqqt 插件。 Node JS 12 中一切运行良好。现在迁移到 Node JS 14 和该函数
on(“connect”) 似乎不再起作用。代理 URL 和凭据没有更改,但我没有连接到代理。此外 on(“error”) 不会返回任何内容。
AWS Lambda 停止支持 Node 12 后,需要迁移。
有什么建议吗?
与 Node JS 18 的行为相同。
下面是我的代码的片段。敏感信息已替换为 xxx。
当使用 NodeJs 14+ 部署此功能时,client.on("connect",function(connack)
不再起作用。
另一个可能很重要的细节。当我使用 AWS 插件和 Docker 在后台从 VSCode 本地运行此函数时,
client.on("connect",function(connack)
似乎正在工作。
'use strict';
const AWS = require('aws-sdk');
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://xxx:1883',{
username: 'xxx'
})
const MqttTargetTopic = 'xxx';
const MqttCheckTopic = 'xxx';
exports.handler = function(event, context, callback) {
context.callbackWaitsForEmptyEventLoop = false;
// Check that the messages only from the whitelisted devices are re-routed
if (event.devi != "xxx" && event.devi != "xxx" && event.devi != "xxx") {
var res = {};
res.processed = "OK - device " + event.devi + " is not whitelisted!";
callback(null, res);
}
else {
// Try to connect to Target MQTT Broker
client.on("connect",function(connack){
console.log("MQTT Client connected " + JSON.stringify(connack));
// If connection successful, try to publish
client.publish(MqttTargetTopic, JSON.stringify(event), { qos: 0, retain: false }, (error) => {
我无法弄清楚为什么之前的实现在 NodeJs 14+ 上停止工作,但我为我的 lambda 函数找到了另一个工作解决方案。我没有使用 mqtt 插件,而是改用了 async-mqtt。
下面的代码适用于 Node Js 16 和 18。
import * as mqtt_async from "async-mqtt";
...
const client = await mqtt_async.connect(...)
await client.publish(topic, data);
await client.end();
...