Skip to content

Instantly share code, notes, and snippets.

@diversemix
Last active February 4, 2022 17:54
Show Gist options
  • Save diversemix/05083af5eb1d5a1ae4bf79918a4f0a6a to your computer and use it in GitHub Desktop.
Save diversemix/05083af5eb1d5a1ae4bf79918a4f0a6a to your computer and use it in GitHub Desktop.
RabbitMQ node demo
#!/bin/bash
npm install
start() {
docker run -d --rm -p 5672:5672 rabbitmq
echo Waiting 5 secs....
sleep 5
}
# start rabbitmq if not running
cat < /dev/null > /dev/tcp/localhost/5672 || start
xterm -geometry 96x24-0+0 -e ./task-generator.js & disown
xterm -geometry 96x24-0-0 -e ./task-consumer.js & disown
xterm -geometry 96x24+0+0 -e ./task-consumer.js & disown
{
"name": "learn-rabbitmq",
"version": "1.0.0",
"description": "",
"main": "task-generator.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"amqplib": "^0.8.0"
}
}
#!/usr/bin/env node
import amqp from 'amqplib'
const queue = 'task_queue';
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
// throws if there is an error
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue(queue, { durable: true });
const get = async () => {
await channel.consume(queue, msg => {
console.log(`Consume: ${msg.content.toString()}`)
channel.ack(msg)
});
await sleep(500 * Math.random());
}
setInterval(get, 500);
#!/usr/bin/env node
import amqp from 'amqplib'
const queue = 'task_queue';
const msg = process.argv.slice(2).join(' ') || "Hello World!";
// throws if there is an error
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue(queue, { durable: true });
const sendSync = async () => {
const toSend = `${msg} - ${Date.now()}`;
const result = await channel.sendToQueue(queue, Buffer.from(toSend), { persistent: true });
console.log(" Sent '%s - %s'", msg, toSend);
}
const sendAsync = () => {
const toSend = `${msg} - ${Date.now()}`;
channel.sendToQueue(queue, Buffer.from(toSend), { persistent: true });
console.log(" Sent '%s", toSend);
}
setInterval(sendAsync , 20);
setTimeout( () => {
connection.close();
process.exit(0);
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment