Skip to content
David Roncancio edited this page Oct 7, 2016 · 10 revisions

RabbitMQ + NodeJS Workshop

Setup

Getting everything ready

That means clone this repo and then create a Rabbitmq instance either via CloudAMQP or on your machine, make sure you have the Rabbitmq management plugin:

RabbitMnger

Clone this repo

$ git clone https://github.com/kuryaki/RabbitWorkshop.git

Install all dependencies

$ cd RabbitWorkshop
RabbitWorkshop/$ npm install

Lets explore whats already created...

Exercise 0 - send emails on register

Basic produce/consume

I. Add Jackrabbit (Super basic AMQP client)

const jackrabbit = require('jackrabbit');
const rabbit = jackrabbit(RABBITMQ_URL);
const exchange = rabbit.topic('jsconf');

There are 3 types of Exchanges Direct, Fanout, Topic, for the sake of the workshop we are going to use topic that can behave as both.

II. Publish the user to a key

exchange.publish(user, { key: 'register.user' })

First parameter is the payload of the message, the second parameter is the options where one of the options is the routing key.

III. Build the service

  • Make a folder named mailer
  • Create an index.js file in it
  • Import the rabbitmq dependencies:
const jackrabbit = require('jackrabbit');
const rabbit = jackrabbit(RABBITMQ_URL);
const exchange = rabbit.topic('jsconf');
  • create the consumer:
const consumer = exchange.queue({ key: 'register.user' });

consumer.consume((data, ack) => {
  console.log(`sending email to ${data.email}`);
  ack();
});
  • launch an instance of the consumer and an instance of the app:

node mailer node app

IV. Experiment with the service

  1. check the dashboard in the queues, how are they named?, how many there are? look for the one that is bind to the key

  2. launch another instance of the mailer, and queue at least 3 more jobs, what happens?

  3. stop all the mailer process and queue at least 3 more jobs, then restart the process, does it queue them?

  4. open the service again what happens? does it send the emails?

  5. try adding a name parameter in the queue options and restart the service, check the dashboard

    const consumer = exchange.queue({ key: 'register.user', name: 'mailer' });
  6. do again the number 2, 3 and 4 from the list above, what happens?