I am using amqplib to transfer messages in my node.js server. I saw an example from RabbitMQ official website:
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'hello';
var msg = 'Hello World!';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer(msg));
console.log(" [x] Sent %s", msg);
});
setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
In this case, the connection is closed in an timeout function. I don't think this is a sustainable way to do it. However, ch.sendToQueue
doesn't have a callback function allowing me to close connection after message is sent. What's a good point to close connection?
I'm using the promise API, but the process is the same. First you need to call channel.close()
and then connection.close()
.
channel.sendToQueue()
returns a boolean.
This is my code using async/await
:
async sendMsg(msg) {
const channel = await this.initChannel();
const sendResult = channel.sendToQueue(this.queue, Buffer.from(msg), {
persistent: true,
});
if (!sendResult) {
await new Promise((resolve) => channel.once('drain', () => resolve));
}
}
async close() {
if (this.channel) await this.channel.close();
await this.conn.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With