Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to publish and disconnect without having to resort to setTimeout?

In the documentation of RabbitMQ they give an example of publishing a message to an exchange and then closing the connection after a 500 delay using setTimeout. I decided to skip the setTimeout, but then my messages were not being sent to the RabbitMQ server if I closed the connection immediately after I ran the publish method. Imagine:

channel.publish('MyExchange', 'MyRoutingKey', Buffer.from('{}'));
await channel.close();
await connection.close();

Is there a better way to close the connection after sending a message than setting a setTimeout?

Link to documentation, at the Putting it all together section: https://www.rabbitmq.com/tutorials/tutorial-five-javascript.html

like image 935
Enthys Avatar asked Dec 31 '25 19:12

Enthys


1 Answers

I should have also provided the connection and channel instantiation to the question above.

The solution was to use createConfirmChannel instead of createChannel. The Channel returned by createConfirmChannel provides a waitForConfirms method which waits to confirm that all messages were received by the server.

For a more in-depth explanation:

  • https://rabbitmq.com/publishers.html#data-safety
  • https://github.com/amqp-node/amqplib/blob/main/examples/waitForConfirms.js
like image 177
Enthys Avatar answered Jan 03 '26 08:01

Enthys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!