我想知道这是否是在不同线程中管理auto_delete队列的正确方法(主要用于测试连接关闭时我不希望RabbitMQ队列停留的问题)
import pika
from threading import Thread
class ConsumerThread(Thread):
def __init__(self, callback, queue):
Thread.__init__(self)
self.setDaemon(True)
self.callback = callback
self.queue = queue
def run(self):
# stablish connection
connection = pika.BlockingConnection(pika.ConnectionParameters(CONNECTION['address'], CONNECTION['port'], CONNECTION['vhost'], CONNECTION['credentials']))
channel = connection.channel()
# create the auto-delete queue
channel.queue_declare(queue=self.queue, auto_delete=True)
# start consuming
channel.basic_qos(prefetch_count=1)
channel.basic_consume(self.callback, queue=self.queue)
channel.start_consuming()
class Factory:
def __init__(self):
self.queue_init = "init.queue"
self.queue_start = "start.queue"
threads = [ConsumerThread(self.init_callback, self.queue_init), ConsumerThread(self.start_callback, self.queue_start)]
for t in threads:
t.start()
def init_callback(self, ch, method, properties, body):
# doing something
def start_callback(self, ch, method, properties, body):
# doing something
答案 0 :(得分:0)
RabbitMQ团队监控the rabbitmq-users
mailing list,有时只回答StackOverflow上的问题。
Pika不是线程安全的。您必须确保BlockingConnection
方法调用发生在运行连接和通道的同一线程上。基于你的代码,我不确定这会发生,因为你在Factory
类中调用回调,这看起来很奇怪。为什么不在ConsumerThread
中使用这些方法?
Pika 0.12
及更高版本将包含一个add_callback_threadsafe
方法,该方法将安排在ioloop线程上执行的方法。