Last active
July 8, 2024 15:40
-
-
Save eduardo-matos/2eb06ec4c6354e0f48ea3b60889c24f1 to your computer and use it in GitHub Desktop.
RabbitMQ graceful shutdown in NodeJS
This file contains 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
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(); |
very nice !
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for this code!