Search code examples
rabbitmqpika

How to consume all RabbitMQ messages other than specified in routing_key?


RabbitMQ allows distribute messages over several queues based on routing_key matching. For exchange of type='topic' one can specify wildcard symbols which allows more flexible filtering (than in case of type='direct' exchange), they are:

* (star) can substitute for exactly one word.
# (hash) can substitute for zero or more words.

E.g., for queue with routing_key='A.B.*' the exchange is pushing all the messages with routing_key of the patterns 'A.B.A', 'A.B.1', 'A.B.XXX', etc.

In my use case I need two queues bound to the same exchange, one queue receives all messages with routing_key='A.B.A' and another queue receives all other messages which is not matching to 'A.B.A'. It is not a big deal to do it for the first queue but I cannot really find anything in tutorials which helps me with the second queue...

Please, would be nice to have an example in python + pika library.


Solution

  • Could you clarify your requirement of bound to the same exchange?

    If it's "just" having the messages pushed through the same exchange instead, you could check out alternate exchange

    Basically it's a configuration on your "main" exchange which states that any message that doesn't match any of the bindings to queues bound to it will be transferred to an alternate exchange (can be of different type) for processing.

    A simple setup would be to have that alternate exchange of type fanout, routing all of those unbound messages to a given queue.