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

Viewed 1859

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)
  );
1 Answers
Related