先看看項目根目錄下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