【发布时间】:2021-02-13 21:00:44
【问题描述】:
我尝试在本地运行以下py文件script.py:
from fastapi import FastAPI
import asyncio
import time
app = FastAPI()
@app.get('/async/')
async def func(text: str):
await asyncio.sleep(5)
return {'text': text}
@app.get('/sync/')
async def func(text: str):
time.sleep(5)
return {'text': text}
使用uvicorn script:app --reload
10 个并发请求同步端点http://127.0.0.1:8000/sync/?text=test 时,每个调用需要 5 秒并阻塞下一个调用,总时间为 50 秒
当向异步端点http://127.0.0.1:8000/async/?text=test发出10个并发请求时,每个调用需要5秒,总时间也是5秒,因为它是非阻塞的。
我尝试使用 entrypoint: gunicorn -w 4 -k uvicorn.workers.UvicornWorker script:app 将脚本部署到 Google App Engine,并在本地进行了相同的测试,得到了以下结果:
向同步端点发出 10 个并发请求时,总时间为 12 秒,所有 10 个请求都在同一个实例上执行。 (1000 个并发请求在 20 多个实例上耗时 60 秒)
当向异步端点发出 10 个并发请求时,总时间为 5 秒,所有 10 个请求都在同一个实例上执行。 (1000 个并发请求在 20 多个实例上耗时 30 秒)
为什么在 GAE 上,10 个并发请求的同步代码需要 12 秒而不是 50 秒?
我如何在 GAE 上同时为同步端点运行所有 10 个请求,以在 5 秒内将它们全部获取?
【问题讨论】:
-
你是如何提出这些要求的?
-
使用k6压力测试(10个虚拟用户10次迭代)
标签: python api google-app-engine asynchronous fastapi