答案 0 :(得分:2)
您必须在根目录中创建一个包含以下内容的const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn) {
console.log(`[ ${new Date()} ] Server started`);
return conn.createChannel();
})
.then(function(ch) {
return ch.assertQueue(q).then(function(ok) {
return ch.consume(q, function(msg) {
console.log(
`[ ${new Date()} ] Message received: ${JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)}`,
);
if (msg !== null) {
const response = {
uuid: uuidv4(),
};
console.log(
`[ ${new Date()} ] Message sent: ${JSON.stringify(response)}`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
{
correlationId: msg.properties.correlationId,
},
);
ch.ack(msg);
}
});
});
})
.catch(console.warn);
文件:
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel => {
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg => {
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
},
{ noAck: true },
);
return channel;
});
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve => {
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message), {
correlationId,
replyTo: REPLY_QUEUE,
});
});
const init = async () => {
const channel = await createClient(RABBITMQ);
const message = { uuid: uuid.v4() };
console.log(`[ ${new Date()} ] Message sent: ${JSON.stringify(message)}`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ ${new Date()} ] Message received: ${respone}`);
process.exit();
};
try {
init();
} catch (e) {
console.log(e);
}