node.jsrabbitmqnode-amqpnode-amqplib

Node.js amqplib - not able to implement the reconnect in case of connection close


I am trying to implement a reconnect mechanism when the connection fails to the rabbitmq queue server.This code is only for consuming messages, Below is my code ( the channel Init function takes care of initialising the consumer and binding to the queue ).

connect() {
    let conn = amqp.connect(queueConfig.QUEUE_SERVER_URL + "?heartbeat=60");
    return conn;
}

createConnection(){
    console.log("Trying to connect amqp");
    let self = this;
    self.connection = this.connect()
    .then(function(connection){
        console.log("[AMQP] connected");
        connection.on("error",function(err){
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err.message);
            }
        });
        connection.on("close", function() {
            console.error("[AMQP] reconnecting");
            return setTimeout(createConnection, 1000);
        });
        return connection.createConfirmChannel();
    })
    .then(self.channelInit);
}

On connection failure I am successfully getting the prompt "[AMQP] reconnecting", but after that queue is not getting reconnected, no other prompts are coming in console log.

Please help.


Solution

  • You have a typo in your method. You need use something like setTimeout(createConnection, 1000); instead of your setTimeout(createConnection(), 1000);