在多个队列上发布时,Pika basic_publish挂起

时间:2012-06-15 05:52:19

标签: python rabbitmq amqp pika

我需要在交易所设置多个队列。我想创建一个单独的连接,然后声明多个队列(这个工作)然后,在多个队列上发布消息(这不起作用)。

我设置了一些测试代码来执行此操作,但每次都会在第二次发布时挂起。我认为它不喜欢在不关闭连接的情况下在多个队列上发布,因为当我在单个队列上发布时(即使是单个队列上的多个消息),此代码也可以工作。

我需要添加一些东西才能使其工作吗?我真的希望不必关闭发布之间的联系。此外,当我让我的消费者起来时,当我在多个队列上发送时发送给basic_publish()时,他们看不到任何东西。当我在一个队列上发布时,我确实看到消息几乎立即出现。

#!/usr/bin/env python
import pika


queue_names = ['1a', '2b', '3c', '4d']


# Variables to hold our connection and channel
connection = None
channel = None


# Called when our connection to RabbitMQ is closed
def on_closed(frame):
    global connection
    # connection.ioloop is blocking, this will stop and exit the app
    connection.ioloop.stop()



def on_connected(connection):
    """
    Called when we have connected to RabbitMQ
    This creates a channel on the connection
    """
    global channel #TODO: Test removing this global call

    connection.add_on_close_callback(on_closed)

    # Create a channel on our connection passing the on_channel_open callback
    connection.channel(on_channel_open)



def on_channel_open(channel_):
    """
    Called when channel opened
    Declare a queue on the channel
    """
    global channel

    # Our usable channel has been passed to us, assign it for future use
    channel = channel_


    # Declare a set of queues on this channel
    for queue_name in reversed(queue_names):
        channel.queue_declare(queue=queue_name, durable=True,
                              exclusive=False, auto_delete=False,
                              callback=on_queue_declared)
        #print "done making hash"

def on_queue_declared(frame):
    """
    Called when a queue is declared
    """
    global channel

    print "Sending 'Hello World!' on ", frame.method.queue

    # Send a message
    channel.basic_publish(exchange='',
                          routing_key=frame.method.queue,
                          body='Hello World!')


# Create our connection parameters and connect to RabbitMQ
connection = pika.SelectConnection(pika.ConnectionParameters('localhost'), \
                                   on_connected)

# Start our IO/Event loop
try:
    connection.ioloop.start()
except KeyboardInterrupt:
    print "interrupt"
    # Gracefully close the connection
    connection.close()
    # Loop until we're fully closed, will stop on its own
    #connection.ioloop.start()

1 个答案:

答案 0 :(得分:2)

我的解决方案是让变量跟踪我的所有队列是否都被声明。

在on_queue_declared()中,我会检查这个变量,如果我的所有队列都被声明了,那么我就开始发布消息了。我相信在收回所有Queue.DeclareOks之前尝试发布消息会导致问题。