4.7.4. Publish to a Direct Exchange
The first is to create a sender that routes messages directly to the endpoint that you wish to publish to. Remember that a Direct Exchange requires an exact match, so you are sending to a specific destination. At the same time, bear in mind that multiple queues can bind to the exchange to receive messages routed to the same destination. So it is a specific endpoint that may have multiple consumers.
qpid-config add exchange direct finance
- Python
sender = session.sender('finance;{create:always, node: {type: topic, x-declare: {type: direct}}}')
reports
endpoint on the finance
exchange.
- Python
sender = session.sender('finance/reports') sender.send('Message to all consumers bound to finance with key reports')
sender
will go to queues that have bound to the finance
direct exchange using the key reports
; with one caveat.
The second option is to create a sender that routes messages to the exchange, and use the message subject to control the routing to the specific endpoint. This way you can dynamically decide where messages will go, for example based on the names of keys that are provided at run-time, perhaps in the body of other messages.
- Python
sender = session.sender('finance; {assert: always, node: {type: topic}}') msg = Message('Message to all consumers bound to finance with key reports') msg.subject = 'reports' sender.send(msg)
subject
. You can target different endpoints on that exchange by changing the subject before sending the message. For example, to send copies of the same message to finance/reports
and finance/records
:
- Python
sender = session.sender('finance; {assert: always, node: {type: topic}}') msg = Message('Message for reports and records') msg.subject = 'reports' sender.send(msg) msg.subject = 'records' sender.send(msg)
{assert: always, node: {type: topic}}
is used to ensure that we don't inadvertently connect to a queue with the name finance
bound to the default exchange. Queues and exchanges have separate namespaces, but remember that the default exchange is nameless.
As you can observe in the second case, setting the subject influences where the message is routed. If you use the first method — the sender with the subject in its address — you must be careful not to set the message subject inadvertently. The sender will write the correct subject into the message when you send it if the message subject is blank, but it will not overwrite any message subject that you provide. The first method — the sender with a subject in its address — provides a "default destination" for all messages it sends that do not have a message subject set. You can target other endpoints on the exchange by explicitly setting a subject before sending the message - in which case they go to the exchange for further routing based on your custom subject. Just be aware that setting the message subject determines its routing.