簡體   English   中英

Python RabbitMQ 並發

[英]Python RabbitMQ Concurrency

在 Spring 中,為 rabbitmq-consumer 設置並發非常簡單。 喜歡:

container.setConcurrentConsumers(consumerSize);
container.setMaxConcurrentConsumers(consumerMaxSize);

在python中有可能嗎?

我的 python 代碼如下所示:

async def handle_message(loop):
    connection = await connect(SETTINGS.cloudamqp_url, loop = loop)

    channel = await connection.channel()

    queue = await channel.declare_queue(SETTINGS.request_queue, durable=True)

    await queue.consume(on_message, no_ack = True)

我使用 Thread 解決了我的問題:

我的代碼如下所示:

import threading

from aio_pika import connect, IncomingMessage, Message
import json

class QueueWorker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.connection = None
        self.channel = None
        self.queue = None

    async def init(self, loop):
        self.connection = await connect(cloudamqp_url, loop=loop)
        self.channel = await self.connection.channel()
        await self.channel.set_qos(prefetch_count=1)
        self.queue = await self.channel.declare_queue(queue, durable=True)
        await self.queue.consume(self.callback, no_ack=False)

    async def callback(self, message: IncomingMessage):
        request = json.loads(message.body.decode("utf-8"))
        try:
            handle(request)
        except Exception as e:
            handleException...
        finally:
            await message.ack()

並發消費隊列:

async def listen_queue(loop):
    for _ in range(consumer_count):
        td = QueueWorker()
        await td.init(loop)

注意:靈感來自在 python 線程中使用 rabbitmq 隊列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM