我需要在交换机上设置多个队列。我想创建一个连接,然后声明多个队列(这可行),然后在多个队列上发布消息(这不起作用)。
我设置了一些测试代码来执行此操作,但它每次都在第二次发布时挂断。我认为它不喜欢在不关闭连接的情况下在多个队列上发布,因为当我在单个队列上发布(甚至单个队列上的多条消息)时,此代码有效。
我需要添加一些东西来完成这项工作吗?我真的很想不必关闭发布之间的连接。此外,当我让我的消费者启动时,当我在多个队列上发送到 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()