Node.js在Ubuntu中怎样实现消息队列

作者:袖梨 2026-07-24

在Ubuntu系统中,使用Node.js实现消息队列可以通过多种方式来完成。以下是一些常见的消息队列解决方案及其在Node.js中的实现方法:

Node.js在Ubuntu中如何实现消息队列

1. RabbitMQ

RabbitMQ是一个广泛使用的开源消息代 理和队列服务器。

安装RabbitMQ

sudo apt updatesudo apt install rabbitmq-server

启动RabbitMQ服务

sudo systemctl start rabbitmq-serversudo systemctl enable rabbitmq-server

在Node.js中使用RabbitMQ

安装amqplib库:

npm install amqplib

创建一个简单的生产者和消费者示例:

生产者 (producer.js)

const amqp = require('amqplib');async function sendMessage() {const connection = await amqp.connect('amqp://localhost');const channel = await connection.createChannel();const queue = 'hello';await channel.assertQueue(queue, { durable: false });const message = 'Hello World!';channel.sendToQueue(queue, Buffer.from(message));console.log(" [x] Sent %s", message);setTimeout(() => {channel.close();connection.close();}, 500);}sendMessage().catch(console.warn);

消费者 (consumer.js)

const amqp = require('amqplib');async function receiveMessage() {const connection = await amqp.connect('amqp://localhost');const channel = await connection.createChannel();const queue = 'hello';await channel.assertQueue(queue, { durable: false });console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);channel.consume(queue, message => {console.log(" [x] Received %s", message.content.toString());channel.ack(message);});}receiveMessage().catch(console.warn);

2. Redis

Redis是一个高性能的键值存储系统,也可以用作消息队列。

安装Redis

sudo apt updatesudo apt install redis-server

启动Redis服务

sudo systemctl start redis-serversudo systemctl enable redis-server

在Node.js中使用Redis

安装ioredis库:

npm install ioredis

创建一个简单的生产者和消费者示例:

生产者 (producer.js)

const Redis = require('ioredis');async function sendMessage() {const redis = new Redis();await redis.set('message', 'Hello World!');console.log("Message sent");setTimeout(() => {redis.quit();}, 1000);}sendMessage().catch(console.warn);

消费者 (consumer.js)

const Redis = require('ioredis');async function receiveMessage() {const redis = new Redis();redis.subscribe('message');redis.on('message', (channel, message) => {console.log(`Received message on channel ${channel}: ${message}`);});}receiveMessage().catch(console.warn);

3. Kafka

Kafka是一个分布式流处理平台,适用于高吞吐量的消息传递。

安装Kafka

sudo apt updatesudo apt install kafka

启动Kafka服务

sudo systemctl start kafkasudo systemctl enable kafka

在Node.js中使用Kafka

安装kafkajs库:

npm install kafkajs

创建一个简单的生产者和消费者示例:

生产者 (producer.js)

const { Kafka } = require('kafkajs');const kafka = new Kafka({clientId: 'my-app',brokers: ['localhost:9092']});const producer = kafka.producer();async function sendMessage() {await producer.connect();await producer.send({topic: 'test-topic',messages: [{ value: 'Hello World!' }]});await producer.disconnect();}sendMessage().catch(console.warn);

消费者 (consumer.js)

const { Kafka } = require('kafkajs');const kafka = new Kafka({clientId: 'my-app',brokers: ['localhost:9092']});const consumer = kafka.consumer({ groupId: 'test-group' });async function receiveMessage() {await consumer.connect();await consumer.subscribe({ topic: 'test-topic', fromBeginning: true });await consumer.run({eachMessage: async ({ topic, partition, message }) => {console.log({value: message.value.toString(),});},});}receiveMessage().catch(console.warn);

以上是几种在Ubuntu系统中使用Node.js实现消息队列的方法。根据具体需求选择合适的消息队列解决方案,并参考相应的文档进行配置和使用。

相关文章

精彩推荐