簡體   English   中英

FastAPI `run_in_threadpool` 卡住了

[英]FastAPI `run_in_threadpool` getting stuck

我已經使用異步實現了所有路由。 並遵循 FastAPI 文檔中的所有指南。

每條路由都有多個數據庫調用,沒有異步支持,所以它們是正常的 function 像這樣

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 如此所述,線程過多可能會導致問題,您可以使用信號量來屏蔽它們,以設置創建的最大線程數的上限。 在代碼中,讀起來大致像

# 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)

暫無
暫無

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

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