簡體   English   中英

關閉/修改來自 FASTAPI 端點的現有 aio_pika 連接

[英]Close/modify an existing aio_pika connection from a FASTAPI endpoint

我使用 aio_pika 作為 rabbitmq 的健壯接口。 FASTAPI 啟動事件創建一個 aio_pika 通道並開始使用一個隊列,如下所示。 我需要做的是有一個端點來關閉/修改這個已經在運行的連接。 這允許另一個遠程應用程序關閉/修改此使用者。

我想要這個端點,但我不知道如何將已經由 FASTAPI 啟動事件實例化的 swarm_connection 傳遞給端點。

#The endpoint I need, but how to pass in swarm_connection?
@app.get("/close")
async def close_pika():
    swarm_connection.close()

到目前為止,我正在努力啟動的代碼

@app.on_event("startup")
def startup():
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(main(loop))

async def main(loop):
    #RabbitMQ
    swarm_connection = await aio_pika.connect_robust(host=host,
                                               port=5672,
                                               login=login,
                                               password=pass,
                                               loop=loop
                                               )
    # Creating channel
    swarm_channel = await swarm_connection.channel()
    # Maximum message count which will be processing at the same time.
    await swarm_channel.set_qos(prefetch_count = 1)

    org1_queue = await swarm_channel.declare_queue('org1', auto_delete=False, durable=True, arguments={'x-max-priority':1})
    await org1_queue.consume(solve_problem_test)

asyncio.wait方法可以等待幾個異步任務中的第一個完成(如果使用參數return_when=asyncio.FIRST_COMPLETED運行)。 所以一個想法是使用asyncio.Event作為信號。 修改main方法中的最后一行以等待隊列或設置的事件,然后在/close端點中設置事件。 類似於以下內容:

closing_connection = asyncio.Event()

@app.get("/close")
async def close_pika():
    closing_connection.set()

# ...
async def main(loop):
    # ...
    _, pending = await asyncio.wait(
        [org1_queue.consume(solve_problem_test), closing_connection.wait()],
        return_when=asyncio.FIRST_COMPLETED
    )
    for task in pending:
        task.cancel()

    # Here you can call swarm_connection.close() or whatever you need to do

最后一部分是取消任何未等待的任務。

暫無
暫無

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

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