介绍
RabbitMQ 是一个消息中间件,它实现了 AMQP (Advanced Message Queuing Protocol) 协议。本教程将带你了解如何使用 RabbitMQ 进行简单的消息发送和接收。
安装与配置
1. 安装 RabbitMQ
- Ubuntu:
```bash
sudo apt update
sudo apt install rabbitmq-server
```
- macOS:
```bash
brew install rabbitmq
```
2. 启动服务
```bash
sudo service rabbitmq-server start
```
3. 配置环境
- 创建用户:
```bash
rabbitmqctl add_user myuser mypass
```
- 设置管理员权限:
```bash
rabbitmqctl set_user_tags myuser administrator
```
- 设置权限:
```bash
rabbitmqctl set_permissions -p / myuser ".*" ".*" ".*"
```
发布/订阅模型
发布/订阅模型允许消息被广播到所有订阅者。
1. 创建生产者
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
message = "Hello, world!"
channel.basic_publish(exchange='logs', routing_key='', body=message)
print(" [x] Sent %r" % message)
connection.close()
```
2. 创建消费者
```python
import pika
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs', queue=queue_name)
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
```
工作队列
工作队列用于处理任务,确保每个消息被处理一次。
1. 创建生产者
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
message = "A new task"
channel.basic_publish(exchange='',
routing_key='task_queue',
body=message,
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
))
print(" [x] Sent 'A new task'")
connection.close()
```
2. 创建消费者
```python
import pika
import time
def callback(ch, method, properties, body):
print(" [x] Received %r" % body.decode())
time.sleep(body.count(b'.'))
print(" [x] Done")
ch.basic_ack(delivery_tag = method.delivery_tag)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()
```
路由
路由模式允许根据不同的规则发送消息到不同的队列。
1. 创建生产者
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
severity = "info"
message = "Info: Check plugin x"
channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
```
2. 创建消费者
```python
import pika
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
severities = ['error', 'warning']
for severity in severities:
queue_name = severity
channel.queue_declare(queue=queue_name)
channel.queue_bind(exchange='direct_logs', queue=queue_name, routing_key=severity)
print(' [*] Waiting for logs. To exit press CTRL+C')
channel.basic_consume(queue='error', on_message_callback=callback, auto_ack=True)
channel.start_consuming()
```
主题交换机
主题交换机允许使用通配符来匹配消息。
1. 创建生产者
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
routing_key = 'kern.critical'
message = 'A critical kernel error'
channel.basic_publish(exchange='topic_logs', routing_key=routing_key, body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()
```
2. 创建消费者
```python
import pika
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
binding_keys = ['kern.*', '*.critical']
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs', queue=queue_name, routing_key=binding_key)
print(' [*] Waiting for logs. To exit press CTRL+C')
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()