发布于2026-07-16 阅读(0)
扫一扫,手机访问
在Ubuntu上搭建消息队列?RabbitMQ和Kafka无疑是两大主力选手。下面直接进入实操环节,分别走一遍两者的安装、配置和简单的Node.js收发示例,保证每一步都能复现。

安装RabbitMQ:
sudo apt update
sudo apt install rabbitmq-server
启动服务:
sudo systemctl start rabbitmq-server
如果需要Web管理界面,可以启用管理插件(非必需但方便):
sudo rabbitmq-plugins enable rabbitmq_management
安装Node.js客户端库——amqplib:
npm install amqplib
编写代码:一个生产者(发送消息)和一个消费者(接收消息)。
生产者 producer.js
const amqp = require('amqplib');
async function sendMessage() {
const conn = await amqp.connect('amqp://localhost');
const channel = await conn.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();
conn.close();
}, 500);
}
sendMessage();
消费者 consumer.js
const amqp = require('amqplib');
async function receiveMessage() {
const conn = await amqp.connect('amqp://localhost');
const channel = await conn.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();
运行测试:分别开两个终端,先启动消费者,再启动生产者。
node consumer.js
node producer.js
安装Kafka:
sudo apt update
sudo apt install kafka
Kafka依赖Zookeeper,需要先启动Zookeeper,再启动Kafka服务器:
sudo systemctl start zookeeper
sudo systemctl start kafka
创建一个测试主题(如果还没有的话):
kafka-topics --create --topic test --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1
安装Node.js的Kafka客户端——kafka-node:
npm install kafka-node
编写生产者和消费者。
生产者 producer.js
const kafka = require('kafka-node');
const Producer = kafka.Producer;
const client = new kafka.KafkaClient({ kafkaHost: 'localhost:9092' });
const producer = new Producer(client);
producer.on('ready', () => {
producer.send([{ topic: 'test', messages: 'Hello Kafka!' }], (err, data) => {
if (err) { console.error(err); }
else { console.log(data); }
});
});
producer.on('error', (err) => {
console.error(err);
});
消费者 consumer.js
const kafka = require('kafka-node');
const Consumer = kafka.Consumer;
const client = new kafka.KafkaClient({ kafkaHost: 'localhost:9092' });
const consumer = new Consumer(
client,
[{ topic: 'test', partition: 0 }],
{ autoCommit: true }
);
consumer.on('message', (message) => {
console.log(message);
});
consumer.on('error', (err) => {
console.error(err);
});
同样的方式运行测试:
node producer.js
node consumer.js
两个方案都走通了,实际使用时可以根据场景选择——RabbitMQ更轻量、灵活,适合任务队列和路由;Kafka则擅长高吞吐、持久化流处理。更详细的配置建议参考官方文档来定制。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8