介绍
RabbitMQ 是一个开源的消息代理和队列服务器,实现了 AMQP 0-9-1 标准。它能够接收、存储并转发消息数据。本教程将引导你通过一系列步骤来设置并使用 RabbitMQ。
环境准备
安装 RabbitMQ
1. 下载安装包:
```bash
wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.9.15/rabbitmq-server-generic-unix-3.9.15.tar.xz
```
2. 解压并安装:
```bash
tar -xJvf rabbitmq-server-generic-unix-3.9.15.tar.xz
cd rabbitmq_server-3.9.15
./rabbitmq-plugins enable rabbitmq_management
```
3. 启动服务:
```bash
./sbin/rabbitmq-server
```
安装客户端库
1. Python:
```bash
pip install pika
```
基础概念
- Broker: 接收和转发消息的应用,即 RabbitMQ 服务器。
- Publish: 发布消息到交换器 (Exchange)。
- Exchange: 根据绑定规则将消息路由到队列 (Queue)。
- Queue: 存储消息直到它们被消费。
- Consumer: 消费队列中的消息。
- Binding: 队列与交换器之间的关联规则。
第一步: 创建生产者
创建一个简单的 Python 脚本来发送消息。
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
创建名为 'hello' 的队列
channel.queue_declare(queue='hello')
发送消息到 'hello' 队列
message = "Hello World!"
channel.basic_publish(exchange='',
routing_key='hello',
body=message)
print(" [x] Sent %r" % message)
connection.close()
```
第二步: 创建消费者
创建另一个脚本来接收消息。
```python
import pika
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
声明队列,确保生产者和消费者的队列一致
channel.queue_declare(queue='hello')
开始消费队列中的消息
channel.basic_consume(queue='hello',
on_message_callback=callback,
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
```
第三步: 使用交换器
创建直接交换器
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
创建一个名为 'direct_logs' 的直接交换器
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
创建一个随机名称的队列
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
绑定队列到交换器
severities = ['info', 'warning', 'error']
for severity in severities:
channel.queue_bind(
exchange='direct_logs', queue=queue_name, routing_key=severity)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()
```
发送日志到直接交换器
```python
import pika
import sys
severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
message = ' '.join(sys.argv[2:]) or "Hello World!"
channel.basic_publish(
exchange='direct_logs', routing_key=severity, body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()