Setup A Simple RabbitMQ Client in JavaScript

Karthikeyan mg
4 min readJan 6, 2024

--

In this post, I will walk you through the steps to successfully set up and run a RabbitMQ Client using Javascript

Introduction

If you are here, you already know what RabbitMQ is but I will still give a brief introduction. RMQ short for RabbitMQ is a message broker that facilitates inter-service communication in a microservice environment. It is an intermediary that takes care of communication between microservices.

Setup RabbitMQ

You can visit cloudamqp.com and sign in to create your RMQ Server. Once you have created an instance, you can connect to it with the provided connection string. Under the AMQP details section, you will find your URL

Local Setup

Open your favourite IDE. I use VSCode. Create a folder named “RabbitMQ” and run the following commands to initialize a node project.

// create two folders

mkdir publisher
mkdir subscriber

// change directory to publisher
cd publisher/

// initialize a node project
npm init --y

// install neccessary packages
npm install express
npm install amqplib

// change directory to subscriber
cd ../

//repeat the same set of steps
npm init --y
npm install express
npm install amqplib

Overview

The idea here is to create two microservices where one acts as a publisher and the other acts as a subscriber. Publisher pushes message to RabbitMQ Client and Subscriber consumes the message thereby achieving message transfer.

Publisher Microservice

Make sure you are already in the publisher directory if not already. You can move into the publisher directory by running the below command

cd ../publisher/

Create two files

  • index.js
  • rabbitmq.js

Index.js would contain our ExpressJS code and rabbitmq.js would host our RabbitMQclass

// index.js

import express from "express";
import RabbitMQClient from "./rabbitmq.js";

const app = express();

app.use(express.json());

app.get("/", async (req, res) => {
const rmq = new RabbitMQClient("myExchange", "myBindKey");
await rmq.initialize();
await rmq.publish();
res.send("Message Sent!");
});

app.listen(3000, () => {
console.log("Publisher Running!");
});
//rabbitmq.js

import { connect } from "amqplib";

export class RabbitMQClient {
constructor(exchangeName, bindingKey) {
this.exchangeName = exchangeName;
this.bindingKey = bindingKey;
}

async initialize() {
this.connection = await connect(
<YOUR_AMQP_URL>
);
this.channel = await this.connection.createChannel();
this.exchange = await this.channel.assertExchange(
this.exchangeName,
"direct",
{
durable: false,
}
);
}

async publish() {
console.log("Publishing message!");
this.channel.publish(
this.exchangeName,
this.bindingKey,
Buffer.from("Hello from producer")
);
}
}

export default RabbitMQClient;

Make sure you replace <YOUR_AMQP_URL> with the actual URL that you copied.

Now run the Express Server by calling node index.js

You will see the Publisher Running! message on your console.

Subscriber Microservice

Now, make sure you are in the subscriber directory if not already. You can move into the subscriber directory by running the below command

cd ../subscriber/

Here we again create the same two files

  • index.js
  • rabbitmq.js

Here is the code for the same

// index.js

import { RabbitMQClient } from "./rabbitmq.js";

async function listen() {
const rmqInstance = new RabbitMQClient("myExchange", "myBindKey", "myQueue");
await rmqInstance.initialize();
await rmqInstance.subscribe();
}

listen();
import { connect } from "amqplib";

export class RabbitMQClient {
constructor(exchangeName, bindingKey, queueName) {
this.exchangeName = exchangeName;
this.bindingKey = bindingKey;
this.queueName = queueName;
}

async initialize() {
this.connection = await connect(
<YOUR_AMQP_URL>
);
this.channel = await this.connection.createChannel();
this.exchange = await this.channel.assertExchange(
this.exchangeName,
"direct",
{
durable: false,
}
);
}

async subscribe() {
console.log("Waiting For Messages!");
await this.channel.assertQueue(this.queueName);
await this.channel.bindQueue(
this.queueName,
this.exchangeName,
this.bindingKey
);

this.channel.consume(this.queueName, (msg) => {
if (msg !== null) {
console.log("Received message:", msg.content.toString());
this.channel.ack(msg);
}
});
}
}

Make sure you replace <YOUR_AMQP_URL> with the actual URL that you copied.

Now run the Express Server by calling node index.js

You will see the message Waiting For Messages! on your console.

Now you have successfully setup your publisher and subscriber. Let’s now test the same

Let us Verify

Since our publisher is running on port 3000 Let’s open the browser and open http://localhost:3000 . This would trigger your publisher to send a message and the same would be consumed by your subscriber

Below is the same output you would observe if everything went fine

From Publisher
From Subscriber

Conclusion

You’ve successfully managed to setup a RabbitMQ Client, Built 2 microservices and established asynchronous communication between them. Congrats!

--

--