gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:50:32 25 4
gpt4 key购买 nike

我需要在一个交换器上设置多个队列。我想创建一个连接,然后声明多个队列(这行得通),然后在多个队列上发布消息(这行不通)。

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

我需要添加什么才能使这项工作正常进行吗?我真的不想关闭发布之间的连接。此外,当我让我的消费者启动时,当我在多个队列上发送到 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()

最佳答案

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

在 on_queue_declared() 中,我会检查这个变量,如果我所有的队列都已声明,那么我就开始发布消息。我认为在取回所有 Queue.DeclareOks 之前尝试发布消息是导致问题的原因。

关于python - Pika basic_publish 在多个队列上发布时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11045280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com