在我的代码中,这是一个处理程序(无服务器框架)我将消息发送到RabbitMQ,但问题是,当我发送第一条消息时,订阅者不会收到任何内容,而第二封消息则只收到第一条消息,其余的同样发生(当我发送消息时,前一个消息被传递!)。有什么想法吗?
编辑:我已使用非常基本且简单的代码替换了实际代码,但结果仍然相同。
Lambda- create.ts
import { APIGatewayEvent, Context, Callback, Handler } from "aws-lambda";
import { config } from "../common/config";
import publish from "../common/publisher";
export const create: Handler = (event: APIGatewayEvent, context: Context, cb: Callback) => {
console.log('test started');
context.callbackWaitsForEmptyEventLoop = false;
const topic = 'float/push';
const num = Math.random();
const message = JSON.stringify({ floatId: num });
publish(config.PUSH_BROKER_UFRL, config.PUSH_USERNAME, config.PUSH_PASSWORD, topic, message, () => {
console.log('calling the callback');
cb(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
},
body: JSON.stringify({ id: num })
});
});
};
publisher.ts
import { Callback } from 'aws-lambda';
import { Client, connect, MqttClient, Packet } from 'mqtt';
function publish(brokerUrl: string, username: string, password: string, topic: string,
message: string, callback: (() => void)): void {
console.log('publish started');
const client: Client = connect(brokerUrl, {
username,
password
});
client.options.clientId = 'Cashmanager.portal';
client.addListener('connect', () => {
console.log('connected to the queue');
console.log(`message to publish: ${JSON.stringify(message)}`);
client.publish(topic, message, (err, packet) => {
console.log(`err: ` + err);
console.log(`packet: ${JSON.stringify(packet)}`);
callback();
});
});
}
导出默认发布;
来自cloudwatch的示例日志:
START RequestId:ea63e6ca-318f-11e8-b766-b78fb7754d27版本:$ LATEST 2018-03-27T07:24:41.744Z ea63e6ca-318f-11e8-b766-b78fb7754d27测试 开始 2018-03-27T07:24:41.744Z ea63e6ca-318f-11e8-b766-b78fb7754d27发布 开始 2018-03-27T07:24:41.767Z ea63e6ca-318f-11e8-b766-b78fb7754d27已连接 到队列 2018-03-27T07:24:41.767Z ea63e6ca-318f-11e8-b766-b78fb7754d27消息 发布:" {\" floatId \":0.24342369749799642}" 2018-03-27T07:24:41.767Z ea63e6ca-318f-11e8-b766-b78fb7754d27错误: 未定义 2018-03-27T07:24:41.767Z ea63e6ca-318f-11e8-b766-b78fb7754d27数据包: 未定义 2018-03-27T07:24:41.767Z ea63e6ca-318f-11e8-b766-b78fb7754d27召唤 回调END RequestId:ea63e6ca-318f-11e8-b766-b78fb7754d27
答案 0 :(得分:0)
所以答案是你应该在发布这条消息后调用client#end
方法。这可能看起来很麻烦,但如果你想继续一次又一次地通过对Lambda函数的调用发布,我认为这将减少你再次打开连接所需的机会。
client.addListener('connect', () => {
console.log('connected to the queue');
console.log(`message to publish: ${JSON.stringify(message)}`);
client.publish(topic, message, (err, packet) => {
console.log(`err: ` + err);
console.log(`packet: ${JSON.stringify(packet)}`);
client.end(false, () => callback()); //This line should be added then it works as expected
});
});