如何正确检查在Node.js中重新连接后是否打开RabbitMQ通道?

我正在使用amqplib ,我试图实现重新连接机制。 但是,连接重新build立后,看起来我的频道仍然closures。 我该如何解决这个问题? 这是我的代码。

 var pubQueue = []; module.exports = { connect: function (callback) { var self = this; amqp.connect(config.queue.url, function(err, connection) { if (err) { console.error("[AMQP]", err.message); return setTimeout(module.exports.connect, 2000); } 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(module.exports.connect, 2000); }); connection.createChannel(function(err, ch) { console.log('connection is reestablished'); self.channel = ch; return callback ? callback() : false; }); }); }, publish: function (message, callback) { var self = this; var key = this.generateKey(message); var m = new Buffer(JSON.stringify(message)); try { self.channel.assertExchange(config.queue.exchange, 'topic', {durable: false, nowait: true}); self.channel.publish(config.queue.exchange, key, m, {nowait: true}); return callback ? callback() : true; } catch(err) { pubQueue.push({key: key, m: m}); console.log(err); } } } 

connect()将在快速应用程序启动后被调用。 但是publish在每个请求中调用。 这就是为什么我有pubQueue存储丢失的消息。 我没有实现函数重新发送队列中的消息,但我得到了这个错误,我似乎无法包围我的头。

 connection is reestablished { [IllegalOperationError: Channel closed] message: 'Channel closed', stack: 'IllegalOperationError: Channel closed\n at Channel.}