先看看项目根目录下database.py出现问题的逻辑:
import aiomysql pool = None async def _init_db_pool(): global pool if pool is None: pool = await aiomysql.create_pool( host='127.0.0.1', port=3306, user='root', password='helloworld', db='mydatabase', charset='utf8mb4', autocommit=True, minsize=1, maxsize=10, pool_recycle=3600, ) async def get_connection(): return await pool.acquire()
这里我们把连接池的maxsize设定为10, 意味着什么? 这个项目能同时有10个数据库连接句柄,不能搞再多。
再看一下逻辑代码:
async def list_some(limit: int): async with await get_connection() as conn: async with conn.cursor(aiomysql.DictCursor) as cur: await cur.execute(f"SELECT * FROM archive " f"WHERE deleted = 2 " f"order by addtime desc " f"LIMIT {limit}") r = await cur.fetchall() return r
跑到浏览器上测试类似的业务, 访问10下是没问题的, 第11下就挂掉。看控制台,也没有任何报错,想重启项目,没有响应,只能按强制重启。
这个时候10个连接句柄实际一直在await状态, 为什么会这样呢?
我们查看这两个语句
# get_connection方法中的返回语句 return await pool.acquire() # 逻辑取数据库连接时候 async with await get_connection() as conn:
这两段逻辑中, 实际是出现了两个await, 这样导致获取数据库连接这一步发生了莫名其妙的等待。处理访问逻辑就会挂死。
如果尝试删除第二句的await, IDE报错, 只能删除get_connection()方法下的await