本文地址:http://blog.csdn.net/spch2008/article/details/11573313
在学习Kombu Exchange与Kombu Queue的过程中,对Kombu 基础中的代码产生疑问:
connection = Connection('amqp://guest:bupt@172.16.4.1:5672//')
channel = connection.channel()
media_exchange = Exchange('media', 'direct', channel)
video_queue = Queue('video', exchange=media_exchange, routing_key='video', channel=channel)
consumer = Consumer(channel, queues=[video_queue], callbacks=[process_media])
consumer.consume()
上述代码中,Exchange与Queue仅仅是声明,应该是不可以进行操作的,为什么程序没有错误呢?
观察Consumer的构造函数:
def __init__(self, channel, queues=None, no_ack=None, auto_declare=None,
callbacks=None, on_decode_error=None):
if auto_declare is not None:
self.auto_declare = auto_declare
if self.channel:
self.revive(self.channel)
def revive(self, channel):
if self.auto_declare:
self.declare()
def declare(self):
for queue in self.queues:
queue.declare()
如果auto_declare不设值,采用默认None的话,auto_declare = True。所以,对应传入的queue,会依次调用declare()。
而Queue中的declare如下:
def declare(self, nowait=False):
if self.exchange:
self.exchange.declare(nowait)
self.queue_declare(nowait, passive=False)
if self.name:
self.queue_bind(nowait)
return self.name
可见,在该函数中,创建exchange,创建queue,并将exchange与queue进行绑定。