Recently, I am working on Lambda sending message to RabbitMQ. We are using typescript, so the package is
"@types/amqplib": "^0.5.7",
We take the callback example as our references
https://github.com/squaremo/amqp.node/blob/master/examples/tutorials/callback_api/emit_log.js
https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/javascript-nodejs/src/emit_log_topic.js
Here is the detail about all the API
http://www.squaremobius.net/amqp.node/channel_api.html#model_createChannel
The core codes are as follow:
const mq_host = process.env.RMQ_SERVER_ADDRESS;
const mq_virtualHost = process.env.RMQ_SERVER_VIRTUALHOST;
const mq_userName = process.env.RMQ_SERVER_USERNAME;
const mq_password = process.env.RMQ_SERVER_PASSWORD;
export interface RabbitOptions {
host: string;
virtualHost: string;
userName: string;
password: string;
}
const logger = getLogger();
async function RabbitMQ(options: RabbitOptions) {
const hasAllOptions = (opts: RabbitOptions) => {
return !!opts.host && !!opts.virtualHost && !!opts.userName && !!opts.password;
};
if (!hasAllOptions(options)) {
throw new Error(
`options missing one of these parameters: ${JSON.stringify({
host: '
virtualHost: '
userName: '
password: '
})}`
);
}
const opt = options;
const mqConnectString = `amqp://${opt.userName}:${opt.password}@${opt.host}/${opt.virtualHost}`;
const connection = await connectMq();
const channel = await createChannelMq(connection);
async function connectMq(): Promise
return new Promise(function(resolve, reject) {
logger.info(`creating mq connection to host: ${mqConnectString}`);
amqp.connect(
mqConnectString,
(err: Error, conn: any) => {
if (err) {
logger.error(err, 'connectMq failed');
reject(err);
} else {
resolve(conn);
}
}
);
});
}
async function createChannelMq(conn: any): Promise
logger.info(`creating mq channel to host: ${mqConnectString}`);
return new Promise(function(resolve, reject) {
conn.createChannel((err: Error, ch: any) => {
if (err) {
logger.error(err, 'createChannel failed');
return reject(err);
} else {
resolve(ch);
}
});
});
}
return {
async sendToMq(exchangeName: string, routingKey: string, message: string) {
console.log(`sending [${message}] to exchange ${exchangeName} with routingkey = '${routingKey}'`);
channel.publish(exchangeName, routingKey, new Buffer(message));
},
async closeMq() {
setTimeout(() => {
channel.close();
connection.close();
}, 200);
},
};
}
export { RabbitMQ };
The important part is the channel.close() and connection.close(), we need to give some time for the message sending in lambda.
References:
https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/javascript-nodejs/src/emit_log_topic.js
https://github.com/squaremo/amqp.node/blob/master/examples/tutorials/callback_api/emit_log.js
http://www.squaremobius.net/amqp.node/channel_api.html#model_createChannel
https://stackoverflow.com/questions/28921127/how-to-wait-for-a-javascript-promise-to-resolve-before-resuming-function