如何解决AMQP + NodeJS等待频道
我在FeathersJS中有一个服务可以启动与RabbitMQ的连接,问题是如何在接收请求之前等待通道准备就绪:
class Service {
constructor({ amqpConnection,queueName }) {
this.amqpConnection = amqpConnection;
this.queueName = queueName;
this.replyQueueName = queueName + "Reply"
}
async create(data,params) {
new Promise(resolve => {
if (!this.channel) await this.createChannel();
channel.responseEmitter.once(correlationId,resolve);
channel.sendToQueue(this.queueName,Buffer.from(data),{
correlationId: asyncLocalStorage.getStore(),replyTo: this.replyQueueName,});
});
}
async createChannel() {
let connection = this.amqpConnection();
let channel = await connection.createChannel();
await channel.assertQueue(this.queueName,{
durable: false,});
this.channel = channel;
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
this.replyQueueName,(msg) => {
channel.responseEmitter.emit(
msg.properties.correlationId,msg.content.toString("utf8")
);
},{ noAck: true }
);
}
....
}
等待请求期间创建频道似乎是一种浪费。该如何“正确”完成?
解决方法
羽毛服务可以实现setup method,它将在服务器启动时被调用(或者您自己调用app.setup()
):
class Service {
async setup () {
await this.createChannel();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。