Search code examples
javascriptnode.jspromiserabbitmqamqp

How do I reuse a RabbitMQ connection and channel outside of the "setup structure" with the amqp library?


I am trying to build a simple node.js client using the amqp library, that opens a single connection and then a single channel to a RabbitMQ server. I want to reuse the same connection and channel to send multiple messages. The main problem is, that I don't want to write my entire code inside the callback function of the ceateChannel() function.

How do I reuse the channel outside of the callback function and make sure the callback function has finished before I use the channel?

I've tried both the callback way and the promise way but I can't make either of them work. When using the callback method I run into the described problem.

When using promises, I have the problem that I can't keep a reference of the connection and channel outside of the .then() function because the passed variables get destroyed after setting up the connection and channel.


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"

  });
});


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


Solution

  • why you don't use 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
    

    Also if you use amqplib, don't forget to handle close and internal error events, for example like this:

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