You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未显式使用asyncio.gather等时await的作用及aio-pika异步代码疑问

关于aio-pika中async/await使用的疑惑

我正尝试基于aio-pika创建RabbitMQ异步客户端,参考了官方异步消息处理的快速启动代码:

import asyncio
import aio_pika

async def process_message(
    message: aio_pika.abc.AbstractIncomingMessage,
) -> None:
    async with message.process():
        print(message.body)
        await asyncio.sleep(1)


async def main() -> None:
    connection = await aio_pika.connect_robust(
        "amqp://guest:guest@127.0.0.1/",
    )

    queue_name = "test_queue"

    # Creating channel
    channel = await connection.channel()

    # Maximum message count which will be processing at the same time.
    await channel.set_qos(prefetch_count=100)

    # Declaring queue
    queue = await channel.declare_queue(queue_name, auto_delete=True)

    await queue.consume(process_message)

    try:
        # Wait until terminate
        await asyncio.Future()
    finally:
        await connection.close()


if __name__ == "__main__":
    asyncio.run(main())

我对该代码中async/await的使用存在疑惑。通过教程了解到asyncio关键字的用法,但对比后发现该代码采用协程链式调用模式,看起来各方法按顺序执行,功能上类似同步。StackOverflow相关讨论提到无gather()、create_task()等并发方法时,asyncio并无用处,我不确定具体含义。

比如,在connect_robust前加await关键字时,哪些代码能在其内部等待期间运行?我猜测aio-pika库内部使用了gather()等异步方法,因此需要await,但无法确认。

我自己测试了两段代码:

异步

import asyncio

async def count():
    print("One")
    await asyncio.sleep(1)
    print("Two")

async def main():
    await asyncio.gather(count(), count(), count())

if __name__ == "__main__":
    asyncio.run(main())

输出:

One
One
One
Two
Two
Two

同步(我认为aio-pika代码类似此模式)

import asyncio

async def count():
    print("One")
    await asyncio.sleep(1)
    print("Two")

async def main():
    await count()
    await count()
    await count()

if __name__ == "__main__":
    asyncio.run(main())

输出:

One
Two
One
Two
One
Two

请问未显式使用asyncio.gather()、asyncio.create_task()等方法时,await关键字的作用是什么?

内容的提问来源于stack exchange,提问作者Jens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:13:13