0

I have defined enqueueMessage function to enqueue the message to rabbitMQ queue. In the first line of the function I am creating channel. Which means every time I call enqueueMessage a channel is created. Is this the right approach or should I created top level channel variable and reuse it?

If I create top level channel should I do some more coding to handle case channel gets closed automatically for some reason (network broke)

export async function enqueueMessage(queue: string, message: object) {
  const channel = await connection.createChannel();
  await channel.assertQueue(queue);
  channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)));
}
Pavan Kumar
  • 1,715
  • 1
  • 24
  • 48

1 Answers1

0

Creating a channel is cheap but not that much. It depends on the rate of call of this method. but generally, you should create a top-level channel but be aware that channels are not thread-safe so you have to care.

And regarding your next question, yes sure, you have to handle it. there are some Auto Recovery options available in some client libraries. for example in Java you can use this code :

factory.setAutomaticRecoveryEnabled(true);

And in my experience, there are some cases that the connection gets closed on the server so I had to handle AlreadyClosedException too.

AminSojoudi
  • 1,904
  • 2
  • 18
  • 42