Skip to content

Instantly share code, notes, and snippets.

@adeisbright
Last active February 1, 2022 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeisbright/90f41cf7972f6023844134064edd6e20 to your computer and use it in GitHub Desktop.
Save adeisbright/90f41cf7972f6023844134064edd6e20 to your computer and use it in GitHub Desktop.
Integrate RabbitMQ into your application faster and easily

RabbitMQ is a message queueing system also know as a message broker. It is a queue that applications can connect in order to to transfer a message or messages or consume from it. RabbitMQ is a queuing system that is mostly used for building event driven systems. In this Gist, I will share some snippets of code and idea on how to go about MQ assuming you are just getting started.

Table of Contents

  1. Understanding RabbitMQ
  2. Downloading and Installing RabbitMQ
  3. Understanding our project
  4. User Service
  5. Notification Service
  6. Handling issues
  7. Concluding Statement

Understanding RabbitMQ

RabbitMQ or MQ as I will be rererring to it is communication pattern that enables application to communicate with a central location. It provides a middle system that allows decoupled systems to hook into.

MQ finds great use in Microservice architecture or if you plan or building an Event Driven System. When you launch MQ server, every producer and consumer can connect to it. We connect to MQ using a client driver.

Some basic concept to understand are @

consumer

Queue

Producer

Downloading RabbitMQ

On downloading and installation, my focus will be on Windows as that is the operating system I am currently using. This gist will be updated to reflect how to go about it on other OS once I lay my hands on them.

Before downloading MQ on windows, you should ensure your system meets or has the following :

  1. Erlang To download an Erlang OTP , use Erlang OPT

  2. Download RabbitMQ

  3. Install MQ as an administrator

  4. After installing the application, you will have access to the RabbitMQ server. Check your installed Apps and launch the RabbitMQ server.

Understanding our Project

The project we will work on is a user registration system.

When a user joins our platform, we want to send an email to the users account.

We will have two services :

  1. Users
  2. Notification

To implement this , we will use NodeJS.

Create a directory for the project :

mkdir bigjara-rabbit

cd bigjara-rabbit

npm init

npm i express amqplib @sendgrid/mail

producer.js

const amqplib = require("amqplib");

/**
 * @description sends a message to RabbitMQ
 * @param {String} queue a queue to connect to or create if it does not exist
 * @param {Any} message to send to a queue. It can be any type
 */
const sendMessageToQueue = async (queue, message) => {
    try {
        const msgTypes = ["number", "string", "boolean"];

        const connect = await amqplib.connect(process.env.AMQP_URL);
        const channel = await connect.createChannel();
        await channel.assertQueue(queue, {
            durable: false,
        });
        const msg = msgTypes.includes(message)
            ? message
            : JSON.stringify(message);
        channel.sendToQueue(queue, Buffer.from(msg));
        return {
            worked: true,
        };
    } catch (error) {
        console.error(error);
        return {
            worked: false,
        };
    }
};

module.exports = sendMessageToQueue;

Consumer

const amqplib = require("amqplib");

const consumeMessage = async (queue, cb) => {
    const connect = await amqplib.connect(process.env.AMQP_URL);
    const channel = await connect.createChannel();
    await channel.assertQueue(queue, {
        durable: false,
    });

    await channel.consume(queue, (e) => cb(e), { noAck: true });
};

module.exports = consumeMessage;

Usage of the producer

const sendMessageToQueue = require("./producer")

async handleRegistraion(req , res) =>{
try {
const messageQueue = await sendMessageToQueue("jara", {
                name: "Adeleke Bright",
                age: 27,
                career: "Software Engineer",
            });
            if (messageQueue.worked) {
                console.log("It worked");
            }
   res.status(201).json({message : "Send Message"})
  }catch(error){
  res.status(500).json(error)
  }
  }
     

Usage of the Consumer

const consumer = require("./consumer")
const runFunction = async (msg) => {
    console.log(await msg.content.toString());
};
consumer("jara", runFunction);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment