ubuntu

如何在Ubuntu上使用Node.js实现消息队列

小樊
47
2025-10-04 03:30:11
栏目: 编程语言

在Ubuntu上使用Node.js实现消息队列,你可以选择多种消息队列系统,如RabbitMQ、Apache Kafka、Redis等。这里以RabbitMQ为例,介绍如何在Ubuntu上安装和使用它。

步骤1:安装RabbitMQ

  1. 更新包列表

    sudo apt update
    
  2. 安装RabbitMQ服务器

    sudo apt install rabbitmq-server
    
  3. 启动RabbitMQ服务

    sudo systemctl start rabbitmq-server
    
  4. 启用RabbitMQ管理插件(可选)

    sudo rabbitmq-plugins enable rabbitmq_management
    
  5. 访问RabbitMQ管理界面 打开浏览器,访问 http://<你的服务器IP>:15672,默认用户名和密码都是 guest

步骤2:在Node.js项目中使用RabbitMQ

  1. 创建一个新的Node.js项目

    mkdir rabbitmq-nodejs-example
    cd rabbitmq-nodejs-example
    npm init -y
    
  2. 安装RabbitMQ客户端库

    npm install amqplib
    
  3. 编写生产者代码 创建一个文件 producer.js

    const amqp = require('amqplib');
    
    async function sendMessage() {
      try {
        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 ${message}`);
    
        setTimeout(() => {
          channel.close();
          connection.close();
        }, 500);
      } catch (error) {
        console.error(error);
      }
    }
    
    sendMessage();
    
  4. 编写消费者代码 创建一个文件 consumer.js

    const amqp = require('amqplib');
    
    async function receiveMessage() {
      try {
        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 ${queue}. To exit press CTRL+C`);
    
        channel.consume(queue, (msg) => {
          console.log(` [x] Received ${msg.content.toString()}`);
          channel.ack(msg);
        });
      } catch (error) {
        console.error(error);
      }
    }
    
    receiveMessage();
    
  5. 运行生产者和消费者 在两个终端中分别运行:

    node producer.js
    

    node consumer.js
    

    你应该会看到消费者终端接收到生产者发送的消息。

总结

通过以上步骤,你已经在Ubuntu上使用Node.js和RabbitMQ实现了一个简单的消息队列系统。你可以根据需要扩展这个示例,添加更多的功能和复杂性,例如持久化消息、路由、交换机等。

0
看了该问题的人还看了