📅  最后修改于: 2023-12-03 15:03:46.190000             🧑  作者: Mango
Pika网络是一个基于Python语言的、遵循AMQP协议的客户端库。它提供了一种简单、高效的方式来与消息队列系统交互。Pika的主要特点包括:
Pika可以通过pip来安装:
pip install pika
以下是一个简单的Pika生产者示例代码:
import pika
# 建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters(host='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消费者示例代码:
import pika
# 回调函数
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters(host='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()