Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to set up of the binding of exchange and queue (producer vs. consumer)?

Tags:

rabbitmq

amqp

All of the official RabbitMQ examples set up the queues and bindings in the consumer. The Publish/Subscribe tutorial states that

The messages will be lost if no queue is bound to the exchange yet, but that's okay for us; if no consumer is listening yet we can safely discard the message.

This is absolutely not okay for me, because I'm implementing a job worker queue on top of RabbitMQ, and it is important to not lose any messages when the consumer hasn't run yet. Therefore, I'm thinking of establishing the exchange <-> queue routing in the producer. Is there a reason why the examples do it the other way around?

As an aside, is it considered best practice to do the basic exchange/queue/routing setup every time I connect to the RabbitMQ server or just once (ever) to basically configure the RabbitMQ instance? My current approach to publish a message currently looks a bit like this:

const getChannel = () =>    
  ampq.connect() // The real implementation caches the connection
    .then(conn => conn.createChannel())
    .then(channel => channel.assertExchange(...)
      .then(() => channel.assertQueue(...)) // Assert and bind for all queues
      .then(() => channel.bindQueue(...))   // Assert and bind for all queues
    );

const publish = (task, payload) => 
  getChannel().then(channel => 
    channel.publish(exchange, task, payload)
  );
like image 977
Tobi Kremer Avatar asked Jul 11 '17 10:07

Tobi Kremer


1 Answers

Yes, you can declare queues and exchanges in your publisher. There are lots of RabbitMQ use cases out there where users use RabbitMQ as a job worker queue. Queues and exchanges will be declared and created IF they do not already exist. (RabbitMQ doesn't allow you to redefine an existing queue with different parameters and will return an error to any program that tries to do that.)

I would recommend you to define them at runtime, do the basic exchange/queue/routing setup when the application instance starts up (or when the queue/exchange is needed). To make sure that RabbitMQ never lose your queue, you need to declare it as durable. Remember that two things are required to make sure that messages aren't lost: we need to mark both the queue and messages as durable. (https://www.cloudamqp.com/blog/2017-03-14-how-to-persist-messages-during-RabbitMQ-broker-restart.html)

like image 109
Lovisa Johansson Avatar answered Nov 14 '22 22:11

Lovisa Johansson