[rabbitmq-discuss] How to sanely bind one queue to many exchanges?

Nathan Gray n8gray at n8gray.org
Tue Aug 11 20:20:22 BST 2009


Hi folks,

I'm using rabbitmq as an event notification system.  In my application
each client will subscribe to a number of exchanges.  Exchanges may
come and go.  The client cannot be expected to know in advance which
exchanges no longer exist, so they will use exchange.declare(...,
passive=True,...) to find out which ones exist.  However,
exchange.declare in passive mode raises a channel exception and kills
the channel if the exchange doesn't exist.  Assuming I want to use one
channel per client I'm stuck with ugly, racy code to subscribe to
multiple exchanges.  (See the end of the post for the python code to
do it.)  And if something goes wrong and kills the channel I have to
go through the whole dance again.  This seems crazy.

My question is, what's the right way for one client to get messages
from multiple exchanges?  Can one auto-delete queue be bound in
multiple channels, and if so is that the proper approach?  Should I be
making N queues & channels to subscribe to N exchanges?

Also, exchange-exchange binding [1] would solve a lot of problems for
me -- does it work or is it just a proposal?

Thanks,
-n8

-- 
http://n8gray.org

[1]: https://dev.rabbitmq.com/wiki/ExchangeToExchangeBindings

while True:
    chan = connection.channel()
    found = []
    for xc in exchanges:
        try:
            chan.exchange_declare(exchange=xc, passive=True, ...)
            found.append(xc)
        except amqp.exceptions.AMQPChannelException, e:
            if e.amqp_reply_code == 404:
                # Channel got closed.  Open a new channel.
                chan = connection.channel()
            else:
                raise e
    # Sure hope nothing gets deleted at this point!
    qname, _, _ = chan.queue_declare(exclusive=True)
    try:
        for xc in found:
            chan.queue_bind(queue=qname, exchange=xc)
    except amqp.exceptions.AMQPChannelException, e:
        if e.amqp_reply_code == 404:
            # Oops, an exchange got deleted.  Start over.
            continue
        else:
            raise e
    # No exception raised, so we're done (until something
    # else goes wrong & kills the channel...)
    break




More information about the rabbitmq-discuss mailing list