4.6.3. Subscribe to the Default Exchange
To subscribe to the Default Exchange, create a receiver and pass the name of the queue to the constructor. For example, to subscribe to the queue "
quick-publish
", using the Python API:
- C++
Receiver receiver = session.createReceiver('quick-publish');
- Python
receiver = session.receiver('quick-publish')
This receiver can now be used to retrieve messages from the
quick-publish
queue.
To obtain a browse-only view that does not remove messages from the queue:
- C++
Receiver receiver = session.createReceiver('quick-publish; {mode: browse}');
- Python
receiver = session.receiver('quick-publish; {mode: browse}')
If you want to create and subscribe a queue that does not yet exist, for example for your application to request its own copies of messages, use the
create
parameter:
- C++
Receiver receiver = session.createReceiver("my-own-copies-please; {create: always, node: {type: 'queue'}}");
- Python
receiver = session.receiver("my-own-copies-please; {create: always, node: {type: 'queue'}}")
If the queue "
my-own-copies-please
" already exists, then your receiver will connect to that queue. If the queue does not exist, then it will be created (all of this assumes sufficient privileges, of course).
One thing to bear in mind is that if an exchange named "
my-own-copies-please
" exists, your receiver will silently connect to that in preference to creating a queue. This is not what you intended, and will have unpredictable results. To avoid this, you can use the assert parameter, like this:
- C++
try { Receiver receiver = session.createReceiver("my-own-copies-please; {create: always, assert: always, node: {type: 'queue'}}"); } catch(const std::exception& error) { std::cerr << error.what() << std::endl; }
- Python
try: receiver = session.receiver("my-own-copies-please; {create: always, assert: always, node: {type: 'queue'}}") except MessagingError m: print m
Now if "
my-own-copies-please
" already exists and is an exchange, the receiver constructor will raise an exception: "expected queue, got topic
".
Note that although it is an instance of a Direct Exchange, the Default Exchange does not allow multiple bindings using the same key. Each queue is bound to the Default Exchange uniquely. This means that you can only connect to a queue to get messages sent to it; you cannot bind another queue to the exchange in parallel to receive copies of the messages, as you can with other Direct Exchanges.