Skip to content

Instantly share code, notes, and snippets.

@shivarajnaidu
Last active September 15, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivarajnaidu/2e8a6869476a1867ddb65a9872ba0258 to your computer and use it in GitHub Desktop.
Save shivarajnaidu/2e8a6869476a1867ddb65a9872ba0258 to your computer and use it in GitHub Desktop.
RabbitMQ Sample NodeJS code
'use strict';
const amqplib = require('amqplib');
const qName = 'tasks';
const open = amqplib.connect('amqp://localhost');
async function getConnection() {
try {
const connection = await open;
console.log('Connected');
return connection;
} catch (error) {
console.error('Failed To Connect To RabbitMQ Server');
console.log(error);
process.exit(1); // Terminate On Error
}
}
// Get Channel And Check/Create Queue
async function getChannel() {
const connection = await getConnection();
const ch = await connection.createChannel() // Create New Channel
await ch.assertQueue(qName); // Check whether the Q exist or create one..
return ch;
}
// Consume Task
async function consumeTasks() {
const ch = await getChannel();
ch.consume(qName, msg => {
if (msg !== null) {
console.log(msg.content.toString());
ch.ack(msg);
}
});
}
consumeTasks();
'use strict';
const amqplib = require('amqplib');
const qName = 'tasks';
const open = amqplib.connect('amqp://localhost');
let connection;
async function getConnection() {
try {
connection = await open;
console.log('Connected');
return connection;
} catch (error) {
console.error('Failed To Connect To RabbitMQ Server');
console.log(error);
process.exit(1); // Terminate On Error
}
}
connection = getConnection();
// Get Channel And Check/Create Queue
async function getChannel() {
connection = await connection;
const ch = await connection.createChannel() // Create New Channel
await ch.assertQueue(qName); // Check whether the Q exist or create one..
return ch;
}
// Publish Task
async function publishTask() {
const ch = await getChannel();
const message = Buffer.from('Do Something....');
ch.sendToQueue(qName, message);
console.log('Published New Task')
}
// Publish Task For Each 3 sec
setInterval(publishTask, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment