我正在尝试在与 rabbitmq 队列服务器的连接失败时实现重新连接机制。此代码仅用于消费消息,以下是我的代码( channel Init 函数负责初始化消费者并绑定(bind)到队列)。
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);
}
连接失败时,我成功收到提示“[AMQP] 正在重新连接”,但在该队列未重新连接后,控制台日志中没有其他提示。
请帮忙。
最佳答案
你的方法有错别字。你需要使用类似 setTimeout(createConnection, 1000);
的东西而不是您的 setTimeout(createConnection(), 1000);
关于Node.js amqplib - 无法在连接关闭的情况下实现重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52291495/