Search code examples
rabbitmqamqprabbitmq-exchange

To consume a rabbitmq queue, do I really need to declare the exchange and the queue?


In all the examples I find online, I see the exchange and the queue being declared before a messages are consumed. Declaring the exchange seems weird, because, why would I do it? I'm consuming a queue, which might be bound to multiple exchanges (or to none, maybe it just have old messages waiting in it).

also, I can't think of why I would declare a queue. This will require me to know information about the queue that I don't need to know to consume it (like auto_delete and durability).

When I tested it locally, I can consume a queue without declaring anything. It works. So I'm left wondering, why does every example I've seen online, declare the exchange and queue, even if it just consumes it?

thanks!!!


Solution

  • "All" the example you saw are self contained. And they trying to give you a working example. Because in case you don't have all the components setted up, your example will fail.

    In terms of "why I would declare a queue". The real-life example is when your consumer wants to consume messages that are relevant with the current configuration. In this case it will create an exclusive ( no one else can connect to this queue ) and will start consume messages.

    Back to your answer. No you don't need to do this. You can pre-create exchange, binding and queue ahead of time and then just pass the names to the code.