gpt4 book ai didi

python-asyncio - FastAPI `run_in_threadpool` 卡住

转载 作者:行者123 更新时间:2023-12-01 23:05:44 26 4
gpt4 key购买 nike

我已经使用异步实现了所有路由。并遵循 FastAPI 文档中的所有指南。

每个路由都有多个数据库调用,没有异步支持,所以它们是这样的正常功能

def db_fetch(query):
# I take a few seconds to respond
return

为了避免阻塞我的事件循环,我使用 fastapi.concurrancy.run_in_threadpool

现在的问题是,当大量请求到来时,我的新请求被阻止了。即使我关闭浏览器选项卡(取消请求),整个应用程序也会卡住,直到旧请求得到处理。

我在这里做错了什么?

我使用 uvicorn 作为我的 ASGI 服务器。我在具有 2 个副本的 kubernetes 集群中运行。

很少有人怀疑:我是不是生成了太多线程?它是 uvicron 中的一些错误吗?不太确定!

最佳答案

正如您所说的线程过多的问题。在底层,fastapi 使用 starlette,后者又使用 anyio 的 to_thread.run_sync。如所述here ,太多的线程可能会导致问题,您可以使用信号量来屏蔽它们,以设置创建的最大线程数的上限。在代码中,这大致类似于

# Core Library
from typing import TypeVar, Callable
from typing_extensions import ParamSpec
# Third party
from anyio import Semaphore
from starlette.concurrency import run_in_threadpool

# To not have too many threads running (which could happen on too many concurrent
# requests, we limit it with a semaphore.
MAX_CONCURRENT_THREADS = 10
MAX_THREADS_GUARD = Semaphore(MAX_CONCURRENT_THREADS)
T = TypeVar("T")
P = ParamSpec("P")


async def run_async(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
async with MAX_THREADS_GUARD:
return await run_in_threadpool(func, *args, **kwargs)

关于python-asyncio - FastAPI `run_in_threadpool` 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70927983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com