RabbitMQ 是一个开源的消息代理和队列服务器,实现高级消息队列协议 (AMQP)。本教程将引导你完成RabbitMQ的基本设置,并演示如何使用Python来发送和接收消息。
1. 安装RabbitMQ
- 下载并安装RabbitMQ: [https://www.rabbitmq.com/download.html](https://www.rabbitmq.com/download.html)
- 启动服务:
```bash
sudo rabbitmq-server
```
2. 安装Erlang和RabbitMQ插件
- Erlang是RabbitMQ的运行环境。
- 安装管理控制台插件:
```bash
sudo rabbitmq-plugins enable rabbitmq_management
```
3. 访问管理界面
- 访问 `http://localhost:15672/` (默认用户名密码都是`guest`)
1. 安装Pika库
- Pika是一个Python客户端库用于与RabbitMQ工作。
- 使用pip安装:
```bash
pip install pika
```
- 文件: `producer.py`
```python
import pika
def send_message(message):
# 建立到RabbitMQ服务器的连接
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明队列
channel.queue_declare(queue='hello')
# 发送消息
channel.basic_publish(exchange='',
routing_key='hello',
body=message)
print(" [x] Sent '%s'" % message)
connection.close()
if __name__ == '__main__':
send_message('Hello World!')
```
- 文件: `consumer.py`
```python
import pika
def on_message(channel, method_frame, header_frame, body):
print(" [x] Received %r" % body)
def receive_messages():
# 连接到RabbitMQ服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明队列
channel.queue_declare(queue='hello')
# 设置回调函数
channel.basic_consume(queue='hello',
on_message_callback=on_message,
auto_ack=True)
# 开始消费
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
receive_messages()
```
1. 启动生产者
- 运行 `producer.py`:
```bash
python producer.py
```
2. 启动消费者
- 在另一个终端中运行 `consumer.py`:
```bash
python consumer.py
```
```python
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.confirm_delivery()
```
```python
channel.basic_publish(exchange='',
routing_key='hello',
body=message,
properties=pika.BasicProperties(delivery_mode=2))
```
```python
channel.basic_qos(prefetch_count=1)
```
```python
channel.exchange_declare(exchange='logs', exchange_type='fanout')
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
channel.queue_bind(exchange='logs', queue='hello')
```