两个nodejs如何使用消息队列进行异步通信
时间: 2023-11-27 07:50:21 浏览: 40
两个 Node.js 应用程序可以使用消息队列进行异步通信。下面是使用 RabbitMQ 消息队列的代码示例:
在发送者端,使用以下代码连接到 RabbitMQ,并将消息发送到名为 "message_queue" 的队列:
```
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var queue = 'message_queue';
var message = 'Hello World!';
channel.assertQueue(queue, {durable: false});
channel.sendToQueue(queue, Buffer.from(message));
console.log(" [x] Sent %s", message);
});
setTimeout(function() {
connection.close();
process.exit(0);
}, 500);
});
```
在接收者端,使用以下代码连接到 RabbitMQ 并从队列中接收消息:
```
var amqp = require('amqplib/callback_api');
amqp.connect('amqp://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
var queue = 'message_queue';
channel.assertQueue(queue, {durable: false});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);
channel.consume(queue, function(msg) {
console.log(" [x] Received %s", msg.content.toString());
}, {
noAck: true
});
});
});
```
以上代码演示了如何使用 RabbitMQ 消息队列在两个 Node.js 应用程序之间进行异步通信。发送者将消息发布到队列,然后接收者从队列中获取并处理消息。