1

为什么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)
4

1 回答 1

1

原来罪魁祸首是 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-02-16T10:47:27.567 回答