Forked from eduardo-matos/rabbit-graceful-shutdown.js
Created
April 29, 2024 09:13
-
-
Save matheuspl/8f17ca7ea2fd1fef51a30770b82f2f48 to your computer and use it in GitHub Desktop.
RabbitMQ graceful shutdown in NodeJS
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
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment