Ste*_*ons 1 javascript amqp rabbitmq node.js promise
我正在尝试使用 amqp 库构建一个简单的 node.js 客户端,它打开一个连接,然后打开一个到 RabbitMQ 服务器的通道。我想重用相同的连接和通道来发送多条消息。主要问题是,我不想在 ceateChannel() 函数的回调函数中编写我的整个代码。
如何在回调函数之外重用通道并确保在使用通道之前回调函数已完成?
我已经尝试了回调方式和承诺方式,但我无法让它们中的任何一个工作。使用回调方法时,我遇到了所描述的问题。
使用 promise 时,我遇到的问题是我无法在 .then() 函数之外保留连接和通道的引用,因为在设置连接和通道后传递的变量会被破坏。
amqp.connect('amqp://localhost', (err, conn) => {
if (err !== null) return console.warn(err);
console.log('Created connection!');
conn.createChannel((err, ch) => {
if (err !== null) return console.warn(err);
console.log('Created channel!');
//this is where I would need to write the code that uses the variable "ch"
//but I want to move the code outside of this structure, while making sure
//this callback completes before I try using "ch"
});
});
Run Code Online (Sandbox Code Playgroud)
amqp.connect('amqp://localhost').then((conn) => {
return conn.createChannel();
}).then((ch) => {
this.channel = ch;
return ch.assertQueue('', {}).then((ok) => {
return this.queueName = ok.queue;
});
}).catch(console.warn);
Run Code Online (Sandbox Code Playgroud)
你为什么不使用async\await?
const conn = await amqp.connect('amqp://localhost');
const ch = await conn.createChannel();
// after that you can use ch anywhere, don't forget to handle exceptions
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用amqplib,请不要忘记处理close内部error事件,例如:
conn.on('error', function (err) {
console.log('AMQP:Error:', err);
});
conn.on('close', () => {
console.log("AMQP:Closed");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2089 次 |
| 最近记录: |