Search code examples
node.jsrabbitmqnode-amqp

Why do I need a Queue in RabbitMQ publishing?


I am using Node.js with node-amqp to create a simple message queue. Most examples that I see do the following:

  1. Create a connection
  2. Create an exchange
  3. Creat a Queue and Bind it to the Exchange
  4. Publish via the Exchange

In my code, I omit the queue (step 3) since it is not used for publishing.

var _connection = amqp.createConnection(_options);

_connection.on('ready', function() {

    _connection.exchange('myexchange', { type: 'direct', autoDelete: false }, function(ex) {

        ex.publish({hello:'world'});
    });
});

Is this ok? or is there a reason for the queue?


Solution

  • There is nothing wrong with the code that you have. This is a good example of how you can keep your message producer nice and simple / clean.

    However, the code you've shown is only half of the messaging solution. You need both a message producer, as shown, and a message consumer.

    A Message Consumer

    The message consumer is the code that does the real work. It receives a message from a queue to which it is subscribed, and processes that message however you tell it to.

    That's the key, here - a message consumer will consume a message from a queue. If you want to send a message and have it be processed, then, you must have a queue for the message.

    The Postal System Analogy

    Think of this like this:

    When you write a letter (pen and paper), you put it in an envelope. Then you write an address on the envelope and send it through your postal system. The postal system knows what the address means, sends it through various trucks and mail processing centers, and eventually puts it in a mailbox for the recipient.

    It's the same thing with messaging in RabbitMQ.

    You are delivering a letter to a destination. You write an "address" (exchange name, and routing key) on the message and RabbitMQ figures out how to deliver it to the appropriate place.

    With physical mail, your letter is put in a mailbox for someone to read. With RabbitMQ and messaging, your message it put in a queue for some software to read.

    You need a queue for the software to receive the message and process it.

    ...

    P.S. If you're in need of some ground-up materials on RabbitMQ and NodeJS, check out my RabbitMQ For Developers package. It will get you up and running in no time, with the most common RMQ questions and patterns.