簡體   English   中英

fastapi + aiomysql 連接池在 10 次調用后卡住

[英]fastapi + aiomysql connection pool stuck after 10 calls

為什么aiomysql連接池在N次調用后卡住了? (N是maxsize連接數。嘗試了默認的N=10和N=3)

我認為獲得的連接會在退出時自動關閉async with

這是重現的最小腳本:

from fastapi import FastAPI
import aiomysql
import secret

app = FastAPI()

@app.on_event("startup")
async def _startup():
    app.state.pool = await aiomysql.create_pool(host=secret.DB_URL, port=3306, user=secret.DB_USERNAME, password=secret.DB_PASSWORD, db=secret.DB_DATABASE)
    print("startup done")

async def _get_query_with_pool(pool):
    async with await pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute("SELECT 1")
            return await cur.fetchall()

@app.get("/v1/get_data")
async def _get_data():
    return await _get_query_with_pool(app.state.pool)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

原來罪魁禍首是 pool.acquire() 之前的額外等待

async def _get_query_with_pool(pool):
    async with await pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute("SELECT 1")
            return await cur.fetchall()

刪除 pool.acquire() 之前的額外等待,因此:

async def _get_query_with_pool(pool):
    async with pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cur:
            await cur.execute("SELECT 1")
            return await cur.fetchall()

現在連接成功

2021 年第四季度更新:

原來連接池是不值得的。 連接池會導致 mysql8 alter table 永遠鎖定。 只需打開和關閉數據庫連接。

暫無
暫無

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

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