polo
polo

Reputation: 1442

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!!!

Upvotes: 6

Views: 3445

Answers (2)

user1295211
user1295211

Reputation: 390

In general, you don’t need declare exchange and queue in consumer. You must assemble "exchanges/queues" topology somewhere else. It's like schema in database.

But always there are exceptions. When you need "private" queue (exclusive=true) for real-time processing, consumer must know (by configuration) about source exchange and bind own queue to it.

In other case i can imagine situations where publisher declare exchange and consumers can discover it using some convention (pattern) for exchange naming.

Upvotes: 5

Vor
Vor

Reputation: 35109

"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.

Upvotes: 5

Related Questions