2011-03-08 84 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循环导致消息到达。