【发布时间】:2017-01-07 13:11:32
【问题描述】:
官方 RabbitMQ Javascript 教程展示了 amqp.node 客户端库的用法
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'hello';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer('Hello World!'));
console.log(" [x] Sent 'Hello World!'");
});
});
但是,我发现很难在其他地方重用此代码。特别是,我不知道如何导出通道对象,因为它在回调中。例如在我的 NodeJs/Express 应用程序中:
app.post('/posts', (req, res) => {
-- Create a new Post
-- Publish a message saying that a new Post has been created
-- Another 'newsfeed' server consume that message and update the newsfeed table
// How do I reuse the channel 'ch' object from amqp.node here
});
你们有这方面的指导吗?欢迎其他库的建议(因为我刚开始,易用性是我认为最重要的)
【问题讨论】:
-
如果需要导出频道对象,可以在创建频道的文件中使用
module.exports。例如在conn.createChannel回调中调用module.exports.channel = ch。然后,您可以从“需要”通道创建脚本的不同文件中访问它,如下所示:channelCreatingScript.channel. -
它将开始未定义
-
您可以将 export 语句放在外面 - 并为其分配
null或{}。当您通过module.exports.channel分配新值时,它会更新它。 -
是否强制仅在创建通道后进行导出?
-
这种情况下你只需要在回调中做,然后当你使用它时,一定要检查
undefinedTypeErrors。试一试,让我知道。我在下面的答案中写了一个示例代码。
标签: javascript node.js express rabbitmq amqp