Node.js amqplib何时关闭连接

8

我正在使用amqplib在我的node.js服务器中传输消息。我看到了来自RabbitMQ官方网站的一个例子:

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);
});

在这种情况下,连接是在超时函数中关闭的。我认为这不是一个可持续的方法。然而,ch.sendToQueue没有回调函数,允许我在消息发送后关闭连接。什么时候关闭连接比较好呢?

也许是这样,但这是需要测试的。sendToQueue函数在将消息发送到RabbitMQ之前会在内部排队,而conn.close()仅在该内部队列已排空(即所有消息都已发送到服务器并被接收)时才释放连接。编辑:我可能是错的,请阅读此文档:http://www.squaremobius.net/amqp.node/channel_api.html#overview - robertklep
使用 ConfirmChannel 并使用 sendToQueue 方法,可以获得一个回调函数,该函数可用于在服务器确认发布后关闭连接。 - Martin Wickman
1个回答

10

我正在使用 Promise API, 但是流程是一样的。首先需要调用 channel.close(), 然后再调用 connection.close()

channel.sendToQueue() 返回一个布尔值。

  • 当它准备好接受更多消息时,返回 True
  • 当你需要等待通道上的 'drain' 事件才能发送更多消息时,返回 False。

这是我的使用 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();
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接