我想在多个python进程之间共享BlockingChannel
。
为了发送
basic_ack
来自其他python进程。
如何在多个python进程之间共享BlockingChannel
。
以下是代码:
self.__connection__ = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.__channel__ = self.__connection__.channel()
我尝试使用pickle
转储,但是它确实允许转储Channel并给出错误can't pickle select.epoll objects
使用以下代码
filepath = "temp/" + "merger_channel.sav"
pickle.dump(self.__channel__, open(filepath, 'wb'))
目标:
目标是从其他python进程的通道发送basic_ack
。
答案 0 :(得分:4)
在多个线程之间共享通道是一种反模式,您很难在进程之间共享它。
经验法则是每个进程1 connection
和每个线程1 channel
。
您可以通过以下链接阅读有关此问题的更多信息:
如果要将消息使用与多处理结合在一起,通常的模式是让主进程接收消息,将其有效负载传递到工作进程池中,并在完成后对其进行确认。
使用pika.BlockingChannel
和concurrent.futures.ProcessPoolExecutor
的简单示例:
def ack_message(channel, delivery_tag, _future):
"""Called once the message has been processed.
Acknowledge the message to RabbitMQ.
"""
channel.basic_ack(delivery_tag=delivery_tag)
for message in channel.consume(queue='example'):
method, properties, body = message
future = pool.submit(process_message, body)
# use partial to pass channel and ack_tag to callback function
ack_message_callback = functools.partial(ack_message, channel, method.delivery_tag)
future.add_done_callback(ack_message_callback)
以上循环将无休止地消耗example
队列中的消息,并将其提交到进程池。您可以通过RabbitMQ consumer prefetch参数控制要同时处理的消息数量。检查pika.basic_qos
,了解如何在Python中进行操作。