Search code examples
node.jsrabbitmqamqpnode-amqpnode-amqplib

nodejs and rabbitmq app , do i pass around the rabbit connect


i am creating a new nodejs service that is going receiving requests from the frontend , placing that request on rabbitmq, then wait for the response from a microservice that handles that request and then sending the response back to the requesting front end that i get back from rabbit.

my question is when i create the connection to rabbitmq, something like

amqp.connect(process.env.CLOUDAMQP_URL + "?heartbeat=60",
 function(err, conn) {
     if (err) {
       console.error("[AMQP]", err.message);
       return setTimeout(start, 1000);
     }
     conn.on("error", function(err) {
       if (err.message !== "Connection closing") {
         console.error("[AMQP] conn error", err.message);
       }
     });
     conn.on("close", function() {
       console.error("[AMQP] reconnecting");
       return setTimeout(start, 1000);
     });
     console.log("[AMQP] connected");
     amqpConn = conn;
     whenConnected();   });

is it best create this connection in app.js (the top level) and pass this s connection around down to the external modules for each request , or should I create a new connection and submit and wait each request?

thanks for any suggestions


Solution

  • Yes, you should share this connection. Opening a new connection for each request will waste resources and time.