温馨提示×

RabbitMQ消费者Ubuntu上如何编写

小樊
43
2025-12-07 00:06:50
栏目: 智能运维

在Ubuntu上编写RabbitMQ消费者通常涉及以下步骤:

  1. 安装RabbitMQ服务器: 如果你还没有安装RabbitMQ,可以通过以下命令安装:

    sudo apt update
    sudo apt install rabbitmq-server
    
  2. 启用管理插件(可选): 为了方便管理RabbitMQ,可以启用管理插件:

    sudo rabbitmq-plugins enable rabbitmq_management
    

    启用后,你可以通过浏览器访问http://<你的服务器IP>:15672/来管理RabbitMQ。

  3. 创建消费者脚本: 使用你喜欢的编程语言编写消费者脚本。这里以Python为例,使用pika库来编写消费者。

    首先,安装pika库:

    pip install pika
    

    然后,编写消费者脚本consumer.py

    import pika
    
    # 连接到RabbitMQ服务器
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # 声明一个队列,确保队列存在
    channel.queue_declare(queue='hello')
    
    # 定义回调函数来处理接收到的消息
    def callback(ch, method, properties, body):
        print(f"Received {body}")
    
    # 告诉RabbitMQ这个回调函数应该处理哪些消息
    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
    
    print('[*] Waiting for messages. To exit press CTRL+C')
    
    # 开始消费
    channel.start_consuming()
    
  4. 运行消费者脚本: 在终端中运行消费者脚本:

    python consumer.py
    

    这样,你的消费者就会开始监听名为hello的队列,并在接收到消息时打印出来。

其他编程语言示例

Java

如果你使用Java,可以使用RabbitMQ Java Client库。首先添加依赖:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.14.2</version>
</dependency>

然后编写消费者代码:

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            };
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
            });
        }
    }
}

Node.js

如果你使用Node.js,可以使用amqplib库。首先安装库:

npm install amqplib

然后编写消费者代码:

const amqp = require('amqplib');

const QUEUE_NAME = 'hello';

async function startConsumer() {
    const connection = await amqp.connect('amqp://localhost');
    const channel = await connection.createChannel();

    await channel.assertQueue(QUEUE_NAME, { durable: false });

    console.log(' [*] Waiting for messages in %s. To exit press CTRL+C', QUEUE_NAME);

    channel.consume(QUEUE_NAME, message => {
        const msg = message.content.toString();
        console.log(` [x] Received ${msg}`);
    }, { noAck: true });
}

startConsumer().catch(console.warn);

通过这些步骤,你可以在Ubuntu上编写并运行RabbitMQ消费者。根据你的需求选择合适的编程语言和库。

0