目录
- [简介](#简介)
- [安装](#安装)
- [安装 RabbitMQ](#安装-rabbitmq)
- [验证安装](#验证安装)
- [基本概念](#基本概念)
- [发布/订阅模式](#发布-订阅模式)
- [实现](#实现)
- [工作队列模式](#工作队列模式)
- [实现](#实现-1)
- [路由模式](#路由模式)
- [实现](#实现-2)
- [主题模式](#主题模式)
- [实现](#实现-3)
- [RPC 模式](#rpc-模式)
- [实现](#实现-4)
简介
RabbitMQ 是一个开源的消息代理和队列服务器,基于 AMQP 0-9-1 协议。它提供了一种在分布式系统中存储和转发消息的可靠方式。
安装
安装 RabbitMQ
```bash
Ubuntu/Debian
sudo apt-get update
sudo apt-get install rabbitmq-server
CentOS/RHEL
sudo yum install epel-release
sudo yum install rabbitmq-server
```
验证安装
```bash
rabbitmqctl status
```
基本概念
- Exchange (交换器): 接收和发送消息的地方。
- Queue (队列): 存储消息的地方。
- Binding: Exchange 和 Queue 之间的连接规则。
- Routing Key: 用于匹配 Binding 和 Message 的键。
发布/订阅模式
实现
创建 Exchange
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
print(" [*] Waiting for logs. To exit press CTRL+C")
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(queue='', on_message_callback=callback, auto_ack=True)
channel.start_consuming()
```
发送消息
```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()
```
工作队列模式
实现
消费者
```python
import pika
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")
def callback(ch, method, properties, body):
print(" [x] Received %r" % body.decode())
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()
```
生产者
```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 %r" % message)
connection.close()
```
路由模式
实现
消费者
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
severities = ['info']
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
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
severity = 'info'
message = 'Info: Hello World!'
channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
```
主题模式
实现
消费者
```python
import pika
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')
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
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
routing_key = 'kern.critical'
message = 'Kernel Critical msg'
channel.basic_publish(exchange='topic_logs', routing_key=routing_key, body=message)
print(" [x] Sent %r:%r" % (routing_key, message))
connection.close()
```
RPC 模式
实现
服务端
```python
import pika
import time
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def on_request(ch, method, props, body):
n = int(body)
print(" [.] fib(%s)" % n)
response = fib(n)
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id = \
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag=method.delivery_tag)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='rpc_queue')
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)
print(" [x] Awaiting RPC requests")
channel.start_consuming()
```
客户端
```python
import pika
import uuid
def on_response(ch, method, props, body):
if corr_id == props.correlation_id:
response = int(body)
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
result = channel.queue_declare(queue='', exclusive=True)
callback_queue = result.method.queue
channel.basic_consume(queue=callback_queue, on_message_callback=on_response, auto_ack=True)
n = 30
corr_id = str(uuid.uuid4())
channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to=callback_queue,
correlation_id=corr_id,
),
body=str(n))
while not response:
connection.process_data_events()
print(" [.] Got %r" % response)
```
```