pika
pika处理消息可以简单分为以下几个步骤:
- 我们首先创建连接对象,然后启动事件循环。
- 当有连接时,调用on_connected方法。在该方法中创建channel
- channel创建完成,将调用on_channel_open方法。在该方法中,声明了一个queue。
- queue声明成功后,将调用on_queue_declared。在该方法中,调用channel.basic_consume,为RabbitMQ传递的每条消息调用handle_delivery。
- 当RabbitMQ有发送消息,将调用handle_delivery方法传递AMQP Method框架,Header框架和Body
官方给出的示例如下:
import pika
# Create a global channel variable to hold our channel object in
channel = None
# Step #2
def on_connected(connection):
"""Called when we are fully connected to RabbitMQ"""
# Open a channel
connection.channel(on_channel_open)
# Step #3
def on_channel_open(new_channel):
"""Called when our channel has opened"""
global channel
channel = new_channel
channel.queue_declare(queue="test", durable=True, exclusive=