Producer and consumer code to interact with RabbitMQ in nodejs
Here's an example of a producer and consumer setup using Node.js with RabbitMQ. This example assumes you have RabbitMQ running at amqp://localhost
1. Set Up Node.js Environment
Make sure you have Node.js installed on your machine. You can download it from nodejs.org and follow the installation instructions.
2. Install Required Packages
You'll need the amqplib
package to interact with RabbitMQ from Node.js. Install it using npm:
npm install amqplib
3. Producer (send.js)
Create a send.js
file for the producer:
const amqp = require('amqplib');
async function produceMessage() {
try {
// Connect to RabbitMQ server
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
// Declare a queue
const queue = 'hello';
await channel.assertQueue(queue, { durable: false });
// Send a message
const message = 'Hello, RabbitMQ!';
channel.sendToQueue(queue, Buffer.from(message));
console.log(`[x] Sent '${message}'`);
// Close connection
setTimeout(() => {
connection.close();
process.exit(0);
}, 500);
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
produceMessage();
4. Consumer (receive.js)
Create a receive.js
file for the consumer:
const amqp = require('amqplib');
async function consumeMessage() {
try {
// Connect to RabbitMQ server
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
// Declare a queue
const queue = 'hello';
await channel.assertQueue(queue, { durable: false });
console.log(`[*] Waiting for messages in ${queue}. To exit press CTRL+C`);
// Consume messages
channel.consume(queue, (msg) => {
if (msg !== null) {
console.log(`[x] Received ${msg.content.toString()}`);
channel.ack(msg); // Acknowledge message received
}
}, { noAck: false }); // Enable message acknowledgments
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
consumeMessage();
5. Run Producer and Consumer
-
Open two terminal windows or tabs.
-
In the first terminal, run the consumer (
receive.js
):node receive.js
-
In the second terminal, run the producer (
send.js
):node send.js
-
Verify that the producer sends a message (
Hello, RabbitMQ!
) and the consumer receives and prints it.
6. Test Additional Scenarios
- Test with multiple consumers to verify message distribution.
- Test network disruptions or container restarts to ensure message durability and handling of edge cases.
Published on: Jun 18, 2024, 02:34 AM