|
1 | 1 | import amqp, { Channel } from "amqplib";
|
| 2 | +import { User } from "../types"; |
| 3 | +import { processNewUser } from "./matchingService"; |
| 4 | +import { SECONDS } from "../lib/constants"; |
2 | 5 |
|
3 | 6 | let channel: Channel;
|
4 |
| -const rabbit_url = process.env.RABBITMQ_URL || "amqp://localhost"; |
| 7 | +const RABBITMQ_URL = process.env.RABBITMQ_URL || "amqp://localhost"; |
| 8 | +const QUEUE = process.env.MATCHING_SERVICE_QUEUE || "matching-service"; |
5 | 9 |
|
6 | 10 | /**
|
7 | 11 | * Establish a connection to RabbitMQ
|
8 | 12 | */
|
9 | 13 | export const initRabbitMQ = async (): Promise<void> => {
|
10 | 14 | try {
|
11 |
| - const connection = await amqp.connect(rabbit_url); |
| 15 | + const connection = await amqp.connect(RABBITMQ_URL); |
12 | 16 | channel = await connection.createChannel();
|
13 | 17 | console.log("Connected to RabbitMQ");
|
| 18 | + |
| 19 | + // Subscribe to the queue upon successful connection |
| 20 | + await subscribeToQueue<User>(QUEUE, processNewUser); |
| 21 | + |
| 22 | + // when connection close, initiate reconnection |
| 23 | + connection.on("close", async () => { |
| 24 | + await reconnectRabbitMQ(); |
| 25 | + }); |
14 | 26 | } catch (err) {
|
15 |
| - console.error("RabbitMQ connection error:", err); |
| 27 | + console.error( |
| 28 | + "Error initialising connection with RabbitMQ connection error:", |
| 29 | + err, |
| 30 | + ); |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * This will only trigger after an initial connection is made |
| 36 | + */ |
| 37 | +export const reconnectRabbitMQ = async (): Promise<void> => { |
| 38 | + const reconnectDelay = 30 * SECONDS; |
| 39 | + while (true) { |
| 40 | + try { |
| 41 | + await initRabbitMQ(); |
| 42 | + break; // Break out of the loop if successfully connected |
| 43 | + } catch (err) { |
| 44 | + console.log( |
| 45 | + `Retrying to connect to RabbitMQ in ${reconnectDelay} seconds...`, |
| 46 | + ); |
| 47 | + await new Promise((resolve) => setTimeout(resolve, reconnectDelay)); |
| 48 | + } |
16 | 49 | }
|
17 | 50 | };
|
18 | 51 |
|
|
0 commit comments