【问题标题】:Node.js amqplib when to close connectionNode.js amqplib 何时关闭连接
【发布时间】:2019-11-21 02:07:08
【问题描述】:

我正在使用amqplib 在我的 node.js 服务器中传输消息。我从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);
});

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

【问题讨论】:

  • 也许,但这是你需要测试的东西,sendToQueue 函数在将消息发送到 RabbitMQ 之前在内部排队,conn.close() 将仅在内部队列耗尽时释放连接(即所有消息都发送到服务器并由服务器接收)。 编辑:我可能错了。阅读:squaremobius.net/amqp.node/channel_api.html#overview
  • ConfirmChannel 与 sendToQueue 结合使用会为您提供一个回调,一旦服务器确认发布,该回调可用于关闭连接

标签: javascript node.js rabbitmq


【解决方案1】:

我正在使用 promise API,但过程是相同的。首先您需要拨打channel.close(),然后拨打connection.close()

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

  • 当它准备好接受更多消息时为真
  • 当您需要在发送更多消息之前等待通道上的 '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();
  }

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2016-11-08
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多