python 操作 RabbitMQ
时间: 2023-10-14 18:26:37 浏览: 119
Python可以使用pika库来操作RabbitMQ。
以下是使用pika库连接RabbitMQ,创建队列并发送消息的示例代码:
```python
import pika
# 连接RabbitMQ服务器
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()
```
以下是使用pika库连接RabbitMQ,接收消息的示例代码:
```python
import pika
# 连接RabbitMQ服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 创建队列
channel.queue_declare(queue='hello')
# 定义回调函数,用于处理接收到的消息
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 订阅队列
channel.basic_consume(queue='hello',
auto_ack=True,
on_message_callback=callback)
print(' [*] Waiting for messages. To exit press CTRL+C')
# 开始接收消息
channel.start_consuming()
# 关闭连接
connection.close()
```
以上是pika库的使用示例,更多关于pika库的详细使用可以参考官方文档:https://pika.readthedocs.io/en/stable/
阅读全文
相关推荐














