问题描述
我在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();
}
}