2011-03-08 121 views
4

如果我運行以下代碼,傳遞給consumer的回調(測試)從不觸發。Python Kombu消費者未通知rabbitmq消息(queue.get確實有效)

但是,如果我留意rabbitmq GUI,我確實看到該消息被檢索(但未被確認)。所以看起來消費者正在收到消息,但不會將它傳遞給我的回調。如果我將no_ack設置爲true,則消息會從隊列中消失,而不會調用回調。

hn = "..." 
usr = "..." 
pwd = "..." 
vh = "/" 
port = 5672 
rkey = "some.routing.key" 
qname = "some-queue-name" 
exchangeName = "MyExchange" 

connection = BrokerConnection(hostname=hn, 
           userid=usr, 
           password=pwd, 
           virtual_host=vh, 
           port=port) 

connection.connect() 
ch = connection.channel() 

# Create & the exchange 
exchange = Exchange(name=exchangeName, 
       type="topic", 
       channel=ch, 
       durable=True) 

exchange.declare() 

# Temporary channel 
ch = connection.channel() 

# Create the queue to feed from 
balq = Queue(name=qname, 
       exchange=exchange, 
       durable=True, 
       auto_delete=False, 
       channel=ch, 
       routing_key=rkey)   

# Declare it on the server 
balq.declare(); 

def test(b,m): 
    print '** Message Arrived **' 

# Create a consumer 
consumer = Consumer(channel=connection.channel(), 
        queues=balq, 
        auto_declare=False, 
        callbacks = [test] 
        ) 

# register it on the server 
consumer.consume(no_ack=False); 

print 'Waiting for messages' 
while(True): 
    pass 

但是,下面的代碼不會正常工作(我能順利拿到並確認該消息):

m = balq.get(no_ack=False) 
m.ack() 
print m 

但整個點是保持同步的。所以,我的回調一定是錯誤的..

回答

5

原來是一個簡單的錯誤。加入

connection.drain_events() 

while循環導致消息到達。