From a2e989454d153cbf869e56c1ed48550739634132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tr=E1=BA=A7n=20L=C3=AA=20Ki=E1=BB=87t?= <53214756+Kettailor@users.noreply.github.com> Date: Thu, 23 Oct 2025 17:01:28 +0700 Subject: [PATCH] Retry RabbitMQ connection in order service --- order/src/app.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/order/src/app.js b/order/src/app.js index a5ba624..995aadf 100644 --- a/order/src/app.js +++ b/order/src/app.js @@ -29,13 +29,29 @@ class App { } async setupOrderConsumer() { - console.log("Connecting to RabbitMQ..."); - const delay = config.rabbitMQConnectDelayMs; - setTimeout(async () => { + + const scheduleRetry = () => { + console.log(`Retrying RabbitMQ connection in ${delay}ms...`); + setTimeout(connectToRabbitMQ, delay); + }; + + const connectToRabbitMQ = async () => { + console.log("Connecting to RabbitMQ..."); + try { const connection = await amqp.connect(config.rabbitMQURI); console.log("Connected to RabbitMQ"); + + connection.on("close", () => { + console.warn("RabbitMQ connection closed"); + scheduleRetry(); + }); + + connection.on("error", (error) => { + console.error("RabbitMQ connection error:", error.message); + }); + const channel = await connection.createChannel(); await channel.assertQueue(config.orderQueue, { durable: true }); @@ -65,8 +81,11 @@ class App { }); } catch (err) { console.error("Failed to connect to RabbitMQ:", err.message); + scheduleRetry(); } - }, delay); + }; + + setTimeout(connectToRabbitMQ, delay); } start() {