Skip to content

Instantly share code, notes, and snippets.

@eduardo-matos
Last active July 8, 2024 15:40
Show Gist options
  • Save eduardo-matos/2eb06ec4c6354e0f48ea3b60889c24f1 to your computer and use it in GitHub Desktop.
Save eduardo-matos/2eb06ec4c6354e0f48ea3b60889c24f1 to your computer and use it in GitHub Desktop.
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) => {
messagesBeingProcessed++;
console.log('Sleeping...');
await sleep(20000);
console.log('Acking message...');
channel.ack(rawMsg);
console.log('Done!');
messagesBeingProcessed--;
}, { 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));
}
main();
@gander
Copy link

gander commented Jan 27, 2021

Thanks a lot for this code!

@benjaminW78
Copy link

very nice !

@Spirit-Sound
Copy link

Thanks!

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