Using RabbitMQ with NodeJS
I enjoy trying out different technologies to see what’s new or available. RabbitMQ is one of my recent explorations. In short, RabbitMQ is a free and open source messaging broker.
Many cloud providers already have queue solutions, which are easy to work with. But it is always nice to know which options are available if we need to develop something on the ground.
Installing RabbitMQ on Mac begins by downloading it using Homebrew.
brew install rabbitmq
Installing RabbitMQ on something Ubuntu Linux can be more involved. Here are the steps for installing RabbitMQ on Linux.
Installing on Windows can be done using choco install rabbitmq
, or you can use a Windows installer. Here’s more information on installing RabbitMQ on Windows.
Interacting with RabbitMQ is straightforward. In this example, we will write a message to the queue using NodeJS (TypeScript).
First, initialize a NodeJS project (this will ask you a few simple questions about your project).
npm init
We will also want to install TypeScript for our project.
npm install TypeScript
Then we can initialize our TypeScript project.
npx tsc –init
Once we initialize TypeScript, we can run it in the background to build our TypeScript files into JavaScript files.
tsc –watch
Now we will install the NodeJS package to interact with an Advanced Message Queueing Protocol (AMQP) for interacting with RabbitMQ.
npm install amqplib
npm install @types/amqplib
Then we want to create a queue.ts
file for our code.
The code to send a message on the queue (enqueue) is below.
The code to read a message (dequeue) is below.
Full source code for an example: https://github.com/chadmichel/RabbitMQTest
RabbitMQ can be configured in various ways depending on your needs. That is probably one of its key advantages; it is very versatile as a queue technology. The RabbitMQ team has good examples of many of these configurations at https://www.rabbitmq.com/tutorials.
Have you tried out RabbitMQ? If so, share your thoughts in the comments below.