我正在尝试构建一个小型库来抽象 amqplib 与 RabbitMQ 通信所需的一些样板。我正在使用 promises api 和 async/await 语法。我正在尝试使用一些方法构建一个类,以与其他几个服务器和客户端一起使用。我在网上搜索过,绝大多数例子都是直接的、小规模的教程。
这是我目前对messages.js的了解:
const amqp = require('amqplib');
module.exports = class MQ {
constructor(user, password, host, port) {
this.conn;
this.uri = 'amqp://' + user + ':' + password + '@' + host + ':' + port;
this.channel;
this.q = '';
}
async setupConnection() {
this.conn = await amqp.connect(this.uri);
this.channel = await this.conn.createChannel();
await this.channel.assertQueue(this.q, { durable: false });
}
send(msg) {
this.channel.sendToQueue(this.q, Buffer.from(msg));
console.log(' [x] Sent %s', msg);
}
async recv() {
await this.channel.consume(this.q), (msg) =>{
const result = msg.content.toString();
console.log(`Receive ${result}`);
};
}
}
这是 setup.js 的代码:
const MQ = require('./message');
msgq = new MQ('guest', 'guest', 'localhost', '5672')
msgq.setupConnection();
msgq.send('Test this message');
我尝试发送消息时收到的错误是“TypeError:无法读取未定义的属性'sendToQueue'。” 显然通道属性没有被正确初始化。我将 async/await 包含在 try/catch 块中并得到相同的错误。
关于 Node.js 中的类/方法,我有什么遗漏吗?
我认为这与承诺的解决有关。当我将对 sendToQueue() 的调用移至 setupConnection() 方法时,将发送消息。
所以看来我需要找到一种方法让 send 方法等待 setup 方法的解析。