如何使用 amqp 库在“设置结构”之外重用 RabbitMQ 连接和通道?

Ste*_*ons 1 javascript amqp rabbitmq node.js promise

我正在尝试使用 amqp 库构建一个简单的 node.js 客户端,它打开一个连接,然后打开一个到 RabbitMQ 服务器的通道。我想重用相同的连接和通道来发送多条消息。主要问题是,我不想在 ceateChannel() 函数的回调函数中编写我的整个代码。

如何在回调函数之外重用通道并确保在使用通道之前回调函数已完成?

我已经尝试了回调方式和承诺方式,但我无法让它们中的任何一个工作。使用回调方法时,我遇到了所描述的问题。

使用 promise 时,我遇到的问题是我无法在 .then() 函数之外保留连接和通道的引用,因为在设置连接和通道后传递的变量会被破坏。


amqp.connect('amqp://localhost', (err, conn) => {

  if (err !== null) return console.warn(err);
  console.log('Created connection!');

  conn.createChannel((err, ch) => {

    if (err !== null) return console.warn(err);
    console.log('Created channel!');

    //this is where I would need to write the code that uses the variable "ch"
    //but I want to move the code outside of this structure, while making sure
    //this callback completes before I try using "ch"

  });
});

Run Code Online (Sandbox Code Playgroud)

    amqp.connect('amqp://localhost').then((conn) => {
      return conn.createChannel();
    }).then((ch) => {
      this.channel = ch;
      return ch.assertQueue('', {}).then((ok) => {
        return this.queueName = ok.queue;  
      });
    }).catch(console.warn);

Run Code Online (Sandbox Code Playgroud)

Его*_*дев 5

你为什么不使用async\await

const conn = await amqp.connect('amqp://localhost');
const ch = await conn.createChannel();
// after that you can use ch anywhere, don't forget to handle exceptions
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用amqplib,请不要忘记处理close内部error事件,例如:

conn.on('error', function (err) {
    console.log('AMQP:Error:', err);
});
conn.on('close', () => {
    console.log("AMQP:Closed");
});
Run Code Online (Sandbox Code Playgroud)

  • 您能分享一下您是如何让它发挥作用的吗?我基本上是尝试在应用程序启动时初始化 RabbitMQ 的连接和通道,然后使用实用函数,我可以调用这些函数来发送消息或在应用程序关闭时关闭连接。理想情况下,我想重用打开的连接/通道,而不是打开新的连接/通道。我正在尝试导出连接和通道(module.exports),但还没有弄清楚。提前致谢! (3认同)
  • 我和@IraklisAlexopoulos 有同样的问题,希望得到任何帮助 (2认同)