A sample of how to use rabbitmq in nodejs as a communication mechanism for apps conversation like microservices.
RabbitMQ use MAQP protocols that support many languages and frameworks. Nodejs is one the client can connect to MAQP!
- Run this following command:
docker run --name rabbitmq -p 5672:5672 rabbitmq
NOTE: 5672 isRabbitMQ
port - Install dependecies
npm i
- Run Publisher to create a random object with two properties:
npm run publish
- Run Consumer that recieve object from queue and dequeue the object:
npm run consume
- use MAQP Protocol
const amqp = require('amqplib')
- create a connection (this is a async func)
const connection = amqp.connect("amqp://localhost");
- build a channel
const channel = await connection.createChannel()
- Check the queue existence, otherwise, create it!
channel.assertQueue(QUEUES.JOBS);
- finally you can send the message to queue
channel.sendToQueue(QUEUES.JOBS, dataMessage)
- use MAQP Protocol
const amqp = require('amqplib')
- create a connection (this is a async func)
const connection = amqp.connect("amqp://localhost");
- build a channel
const channel = await connection.createChannel()
- Check the queue existence, otherwise, create it!
channel.assertQueue(QUEUES.JOBS);
- listen the queue and get message whenever it queued
channel.consume(QUEUES.JOBS, job => {...})
- dequeue the message by
ack
functionchannel.ack(job);