Skip to content

Instantly share code, notes, and snippets.

Last active July 28, 2023 15:02
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
RabbitMQ graceful shutdown in NodeJS
const amqp = require('amqplib');
const uuid = require('uuid')
const CONSUMER_TAG = uuid.v4();
const QUEUE_NAME = 'my_queue'
async function main() {
const conn = await amqp.connect('amqp://guest:guest@localhost:5672/%2F');
const channel = await conn.createChannel();
await channel.assertQueue(QUEUE_NAME);
let messagesBeingProcessed = 0;
console.log('Ready to consume messages...');
channel.consume(QUEUE_NAME, async (rawMsg) => {
await sleep(20000);
console.log('Acking message...');
}, { consumerTag: CONSUMER_TAG });
process.on('SIGTERM', async () => {
await channel.cancel(CONSUMER_TAG);
while(true) {
if (messagesBeingProcessed === 0) break;
await sleep(100);
console.log('Closing channel...');
await channel.close();
console.log('Closing connection...');
await conn.close();
console.log('Ready to shutdown!')
function sleep(timeout) {
return new Promise(resolve => setTimeout(resolve, timeout));
Copy link

gander commented Jan 27, 2021

Thanks a lot for this code!

Copy link

very nice !

Copy link


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment