Python 使rabbitMQ连接可供其他模块访问

Python 使rabbitMQ连接可供其他模块访问,python,rabbitmq,connection,instance,Python,Rabbitmq,Connection,Instance,RabbitMQ最佳实践建议使用长寿命连接,理想情况下分离使用和发布连接,并将每个线程的通道连接到相应的连接。我正在构建一个分布式系统,其中每个部分都需要使用消息并将消息发布到系统的其他部分。类RabbitMQ创建这些连接,将通道附加到它们,并发布消息。另一方面,我有大约10个进程,每个进程在一个线程中,它们必须通过“自己的”通道进行消费/发布。启动时,每个进程创建其通道并绑定其队列 我的问题是如何启动RabbitMQ类的唯一实例,使这两个连接“可访问”到进程,保持这两个连接处于活动状态,并避免

RabbitMQ最佳实践建议使用长寿命连接,理想情况下分离使用和发布连接,并将每个线程的通道连接到相应的连接。我正在构建一个分布式系统,其中每个部分都需要使用消息并将消息发布到系统的其他部分。类RabbitMQ创建这些连接,将通道附加到它们,并发布消息。另一方面,我有大约10个进程,每个进程在一个线程中,它们必须通过“自己的”通道进行消费/发布。启动时,每个进程创建其通道并绑定其队列

我的问题是如何启动RabbitMQ类的唯一实例,使这两个连接“可访问”到进程,保持这两个连接处于活动状态,并避免操作/关闭通道。我尝试在每个模块中导入消息,但是对于每个导入,都有一个类的实例化,因此有两个新连接。我还尝试向类RabbitMQ添加一个单例,以避免在导入上进行多次实例化,但没有成功

我感谢你的帮助

消息传递.py 消费_进程.py
。。。
def connect_消息(自):
channel=self.messaging.create\u consumer\u channel()#
class RabbitMQ:

    def __init__(self):
        self.consume_connection = None
        self.publish_connection = None
        self.initialize_connection()

    def initialize_connection(self):
        self.consume_connection = pika.BlockingConnection(pika.ConnectionParameters(
            host='localhost', socket_timeout=5, client_properties={'connection_name': 'consume_connection'}))
        self.publish_connection = pika.BlockingConnection(pika.ConnectionParameters(
            host='localhost', socket_timeout=5, client_properties={'connection_name': 'publish_connection'}))

    def send_message(self, exchange_name, routing_key, message, channel):
        ...

    def create_consume_channel(self):
        ...

    def create_publish_channel(self):
        ...


Messaging = RabbitMQ()
...
def connect_messaging(self):
    channel = self.messaging.create_consume_channel() # <-- messaging would be the instance of class RabbitMQ
    channel.basic_qos(prefetch_count=100)

    exchange_name = 'abc'
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct')

    result = channel.queue_declare(queue='queue_name')
    queue_1 = result.method.queue
    channel.queue_bind(exchange=exchange_name, queue=queue_1, routing_key='some_routing_key')
    ...    

    def callback_function(ch, method, properties, body):
        ...
        ch.basic_ack(delivery_tag=method.delivery_tag)

    channel.basic_consume(callback_function, queue=queue_1, no_ack=False)
    channel.start_consuming()