RabbitMQ: How to specify the queue to publish to?

user1768830 picture user1768830 · Aug 30, 2013 · Viewed 16.2k times · Source

RabbitMQ's Channel#basicConsume method gives us the following arguments:

channel.basicConsume(queueName, autoAck, consumerTag, noLocal,
    exclusive, arguments, callback);

Giving us the ability to tell RabbitMQ exactly which queue we want to consume from.

But Channel#basicPublish has no such equivalency:

channel.basicPublish(exchangeName, routingKey, mandatory, immediateFlag,
    basicProperties, messageAsBytes);

Why can't I specify the queue to publish to here?!? How do I get a Channel publishing to, say, a queue named logging? Thanks in advance!

Answer

Brian Reischl picture Brian Reischl · May 6, 2014

To expand on @Tien Nguyen's answer, there is a "cheat" in RabbitMQ that effectively lets you publish directly to a queue. Each queue is automatically bound to the AMQP default exchange, with the queue's name as the routing key. The default exchange is also known as the "nameless exchange" - ie its name is the empty string. So if you publish to the exchange named "" with routing key equal to your queue's name, the message will go to just that queue. It is going through an exchange as @John said, it's just not one that you need to declare or bind yourself.

I don't have the Java client handy to try this code, but it should work.

channel.basicPublish("", myQueueName, false, false, null, myMessageAsBytes);

That said, this is mostly contrary to the spirit of how RabbitMQ works. For normal application flow you should declare and bind exchanges. But for exceptional cases the "cheat" can be useful. For example, I believe this is how the Rabbit Admin Console allows you to manually publish messages to a queue without all the ceremony of creating and binding exchanges.