与 aiohttp 服务器并发

Concurrency with aiohttp server

这是我的代码:

import asyncio
import logging
import time

from aiohttp import web

logging.getLogger('aiohttp').setLevel(logging.DEBUG)
logging.getLogger('aiohttp').addHandler(logging.StreamHandler(sys.stderr))

def handle_sync(request):
    web.web_logger.debug('Sync begin')
    time.sleep(10)
    web.web_logger.debug('Sync end')
    return web.Response(text='Synchronous hello')


async def handle_async(request):
    web.web_logger.debug('Async begin')
    await asyncio.sleep(10)
    web.web_logger.debug('Async end')
    return web.Response(text='Asynchronous hello')


async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_get('/sync/', handle_sync)
    app.router.add_get('/async/', handle_async)

    srv = await loop.create_server(app.make_handler(), '0.0.0.0', 8080)
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

我希望有 2 种行为:

但是这两种情况似乎都持续了 20 秒,有人能解释一下为什么吗?

为了能够在此处观察使用异步的好处,您将需要(几乎)同时发送两个单独的请求。

await 调用只是意味着该函数将控制权交给事件循环,这样如果发生任何其他事件,它们可以在不阻塞的情况下得到处理。如果您同时向异步端点发送两个请求,您将看到每个请求都在大约 10 秒内完成。这是因为两个请求是同时处理的:第一个请求不会阻止服务器处理另一个请求。

但是,如果您以类似的方式向同步端点发送两个请求,则第二个请求将花费 20 秒。这是因为同步端点在第一个请求上阻塞,并且在第一个请求完成之前无法开始为第二个请求提供服务。