How do I split up my rabbitMQ code across components?

40 views
Skip to first unread message

louisle...@gmail.com

unread,
Mar 26, 2019, 11:35:54 PM3/26/19
to rabbitmq-users

I want to split my rabbitMQ connection code and call it across different components, so that it (the connection and channel) only initializes ONCE and I can use it whenever instead of having to open the connection again when I want to use it.

What happens right now is, I call the below's code function over and over again everytime I want to pass something to my exchange and queue. (so if I want to pass 20 individual data to rabbitMQ, I ended up opening and closing both the connection and channel 20 times)

Any solutions?

const exchange = "Exchange";
const queue = "Queue";

const passSomeData= async payload => {
  amqp = require("amqplib").connect("amqp://localhost");
  let ch;
  let connection;
  let publish = amqp
    .then(function(conn) {
      connection = conn;
      return conn.createConfirmChannel();
    })
    .then(function(chn) {
      ch = chn;
      ch.assertQueue(queue, { durable: true });
      return ch.assertExchange(exchange, "topic", { durable: true });
    })
    .then(function() {
      const data = {
        content: "x",
        title: "y",
      };
      ch.bindQueue(queue, exchange, "routingKey");

      return ch.publish(exchange, "routingKey", Buffer.from(JSON.stringify(data)), {
        persistent: true
      });
    })
    .then(() => {
      setTimeout(function() {
        connection.close();
      }, 250);
    });
};

module.exports = passSomeData;

Luke Bakken

unread,
Mar 27, 2019, 11:40:09 AM3/27/19
to rabbitmq-users
Hello,

This is a general Javascript question and not one specific to RabbitMQ or the amqplib library.

I believe you can open a connection at the module level and use that within your passSomeData method. Or, passSomeData can lazily open a connection if the module-level "connection" variable is null, and then re-use that connection.

At some point you may need to use a connection pool, but that depends on your use-case and workload.

Thanks,
Luke
Reply all
Reply to author
Forward
0 new messages