Last active
September 15, 2018 12:54
-
-
Save shivarajnaidu/2e8a6869476a1867ddb65a9872ba0258 to your computer and use it in GitHub Desktop.
RabbitMQ Sample NodeJS code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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