重用callback/重用通道的参数

我想在不同的节点模块中重用一个RabbitMQ通道。 由于通道是asynchronous创build的,我不确定最好的方法是将这个通道对象“注入”到其他模块中。

如果可能的话,我想避免像DI容器这样的外部依赖。

下面,你会发现我的简化代码。

提前感谢您的任何build议。

web.js

require('./rabbitmq')(function (err, conn) { ... // Start web server var http = require('./http'); var serverInstance = http.listen(process.env.PORT || 8000, function () { var host = serverInstance.address().address; var port = serverInstance.address().port; }); }); 

rabbitmq.js

 module.exports = function (done) { ... amqp.connect(rabbitMQUri, function (err, conn) { ... conn.createChannel(function(err, ch) { ... // I would like to reuse ch in other modules }); }); } 

someController.js

 module.exports.post = function (req, res) { // Reuse/inject "ch" here, so I can send messages } 

你总是可以将你的频道句柄附加到global对象,并且可以通过模块访问:

 #rabbitmq.js global.ch = ch #someController.js global.ch # <- is the channel instance 

我宁愿把句柄注入到每个函数中,因为我认为它更明确,更容易推理和unit testing。 你可以用部分函数应用程序来做到这一点

与lodash :

 var post = function (req, res, rabbitMQchannel) { // Reuse/inject "ch" here, so I can send messages } var ch = getYourChannel(); # post is function object that accepts two params, and the # third is bound to your channel module.exports.post = _.partialRight(post, ch); 

第三个select是让rabbitmq.js导出一个函数来获取频道。 一个渠道可能是一个单身人士,所以只会有一个实例。 然后,任何一个渠道处理将要求的方法,这将不需要通过function,或全球通道传递的方法。