python对RabbitMQ的简单使用
时间: 2024-06-21 11:00:30 浏览: 234
Python与RabbitMQ的集成通常通过`pika`库来实现,这是一个Python客户端库,用于与RabbitMQ进行交互。以下是一个简单的使用示例:
首先,确保安装了`pika`库,可以通过pip安装:
```shell
pip install pika
```
然后,你可以创建一个生产者(Publisher)和一个消费者(Consumer)来发送和接收消息:
**生产者(Producer):**
```python
import pika
def send_message():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明交换器(Exchange)
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
# 发送消息
routing_key = 'info'
message = 'Hello World!'
channel.basic_publish(exchange='direct_logs', routing_key=routing_key, body=message)
print(f" [x] Sent {message} to {routing_key}")
connection.close()
send_message()
```
**消费者(Consumer):**
```python
import pika
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
def consume_messages():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明队列并自动绑定到交换器
channel.queue_declare(queue='hello')
channel.queue_bind(exchange='direct_logs', queue='hello', routing_key='info')
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
consume_messages()
```
在这个例子中,生产者向名为'direct_logs'的交换器发送消息,使用路由键'info'。消费者会从队列'hello'中接收这些消息。
阅读全文