1. 引言
RabbitMQ 是一个消息中间件平台,它实现了 AMQP (Advanced Message Queuing Protocol) 标准。本教程将指导你如何安装和使用 RabbitMQ。
2. 安装 RabbitMQ
2.1 安装 Erlang
RabbitMQ 基于 Erlang 开发,因此需要先安装 Erlang。
Linux:
```bash
sudo apt-get update
sudo apt-get install erlang
```
macOS:
```bash
brew install erlang
```
2.2 安装 RabbitMQ
Linux:
```bash
sudo apt-get install rabbitmq-server
```
macOS:
```bash
brew install rabbitmq
```
2.3 启动服务
```bash
rabbitmq-server
```
3. 使用 RabbitMQ
3.1 管理界面
- 打开浏览器访问: http://localhost:15672/
- 用户名/密码: guest/guest
3.2 创建虚拟主机
- 虚拟主机相当于隔离的环境。
- 在管理界面中创建一个新的虚拟主机。
3.3 Python 示例
3.3.1 安装 pika
```bash
pip install pika
```
3.3.2 发送消息
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
```
3.3.3 接收消息
```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()
```
4. 高级主题
4.1 工作队列
- 通过设置持久化来确保消息不会丢失。
- 分配消息给空闲的工作进程。
发送方
```python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
message = "A heavy 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
import time
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
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()