我试图通过介绍pika(http://pika.readthedocs.io/en/0.10.0/intro.html#io-and-event-looping)来理解这个代码示例:
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=False, auto_delete=False, callback=on_queue_declared)
# Step #4
def on_queue_declared(frame):
"""Called when RabbitMQ has told us our Queue has been declared, frame is the response from RabbitMQ"""
channel.basic_consume(handle_delivery, queue='test')
# Step #5
def handle_delivery(channel, method, header, body):
"""Called when we receive a message from RabbitMQ"""
print body
# Step #1: Connect to RabbitMQ using the default parameters
parameters = pika.ConnectionParameters()
connection = pika.SelectConnection(parameters, on_connected)
try:
# Loop so we can communicate with RabbitMQ
connection.ioloop.start()
except KeyboardInterrupt:
# Gracefully close the connection
connection.close()
# Loop until we're fully closed, will stop on its own
connection.ioloop.start()
根据handle_delivery
的文档字符串,当我们从RabbitMQ收到消息时应该调用它。但是,我没有看到代码中稍后引用handle_delivery
,也没有在pika 0.10.0源代码中找到它的任何出现:
kurt@kurt-ThinkPad:~/dev/scratch/pika-0.10.0$ grep -r "handle_delivery"
kurt@kurt-ThinkPad:~/dev/scratch/pika-0.10.0$
那么handle_delivery
如何获得'由connection
?
答案 0 :(得分:0)
step4将频道与handle_deivery函数相关联。
# Step #4
def on_queue_declared(frame):
"""Called when RabbitMQ has told us our Queue has been declared, frame is the response from RabbitMQ"""
channel.basic_consume(handle_delivery, queue='test')
频道与步骤#2中的连接相关联
# Step #2
def on_connected(connection):
"""Called when we are fully connected to RabbitMQ"""
# Open a channel
connection.channel(on_channel_open)