我正在使用tsoa生成swagger定义并尝试向rabbitmq发送api请求我正在使用facundoolano实现来连接rabbitmq
import { configuration, random, uuid, amqp } from '../config';
const EventEmitter = require('events');
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const createClient = () => amqp.connect(configuration.amqpUrl)
.then((conn) => conn.createChannel())
.then((channel: any) => {
// create an event emitter where rpc responses will be published by correlationId
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(REPLY_QUEUE,
(msg: any) => channel.responseEmitter.emit(msg.properties.correlationId, msg.content),
{ noAck: true });
return channel;
});
const sendRPCMessage = (channel: any, message: any, rpcQueue: any) => new Promise((resolve, reject) => {
const correlationId = uuid.v4();
// listen for the content emitted on the correlationId event
try {
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, new Buffer(JSON.stringify(message)), { correlationId, replyTo: REPLY_QUEUE })
} catch (error) { reject(error) }
});
但问题是我不知道如何返回请求的响应。我的控制器我试图像这样返回队列响应
@Post()
public async postSurvey(survey: Survey): Promise<Survey> {
var obj: Survey;
await createClient().then((channel) => {
sendRPCMessage(channel, survey, "survey_q_req").then((data) => {
obj = data as Survey;
}).catch((error) => { console.log(error) });
}).catch((error) => { console.log(error) });
return obj
}
如何从rabbitmq的响应队列返回响应
答案 0 :(得分:1)
@Post()
public async postSurvey(survey: Survey): Promise<Survey> {
return createClient()
.then(channel => {
return sendRPCMessage(channel, survey, "survey_q_req")
})
.then(data => {
return data;
})
.catch((error) => { console.log(error) });
}