![](/img/trans.png)
[英]How to share data between multiple threads and processes in Python effectively?
[英]Share RabbitMQ channel between multiple python processes
我想在多個python進程之間共享BlockingChannel
。 為了從其他python進程發送basic_ack
。
如何在多個python進程之間共享BlockingChannel
。
以下是代碼:
self.__connection__ = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.__channel__ = self.__connection__.channel()
我嘗試使用pickle
進行轉儲,但是它確實允許轉儲Channel並給出錯誤can't pickle select.epoll objects
使用以下代碼對can't pickle select.epoll objects
進行can't pickle select.epoll objects
filepath = "temp/" + "merger_channel.sav"
pickle.dump(self.__channel__, open(filepath, 'wb'))
目標:
目標是從其他python進程的通道發送basic_ack
。
在多個線程之間共享一個通道是一種反模式,您很難在進程之間共享它。
經驗法則是每個進程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 使用者預取參數控制要同時處理的消息數量。 檢查pika.basic_qos
以了解如何在Python中進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.