Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js amqplib when to close connection

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?

like image 433
zhangjinzhou Avatar asked Aug 15 '17 18:08

zhangjinzhou


1 Answers

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.

  • True when it's ready to accept more messages
  • False when you need to wait for the 'drain' event on channel before sending more messages.

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();
  }
like image 170
rtribaldos Avatar answered Sep 24 '22 13:09

rtribaldos