Node.js amqplib何时关闭连接

zha*_*hou 6 javascript rabbitmq node.js

我正在使用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);
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,连接将在超时功能中关闭。我认为这不是可持续的方式。但是,ch.sendToQueue没有回调函数,允许我在发送消息后关闭连接。紧密连接有什么好处?

Ric*_*dos 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();
  }
Run Code Online (Sandbox Code Playgroud)