asyncpg/fastapi创建的连接数超过了连接池的限制。
创始人
2024-09-21 08:00:41
0

可以通过设置 max_size 参数来控制连接池的大小,避免创建过多的连接。同时,还可以使用 await connection.release() 来释放连接,以便其他请求可以获取连接。

示例代码:

import asyncio
import asyncpg
from fastapi import FastAPI

app = FastAPI()
dsn = "postgresql://user:password@localhost/mydatabase"

async def connect_to_db(app):
    app.pool = await asyncpg.create_pool(dsn=dsn, max_size=10)

@app.on_event("startup")
async def startup():
    await connect_to_db(app)

@app.on_event("shutdown")
async def shutdown():
    await app.pool.close()

@app.get("/")
async def root():
    async with app.pool.acquire() as connection:
        # Use connection
        pass
        await connection.release() # 释放连接

在上面的代码中,max_size 参数设置了连接池的最大大小为 10,确保不会创建超过 10 个连接。同时,在 root() 函数中,使用 async with app.pool.acquire() as connection: 来获取连接,并在使用后使用 await connection.release() 来释放连接。这样可以确保每次只使用一个连接,并避免创建过多的连接。

相关内容

热门资讯

透视详细!wepoker辅助器... 透视详细!wepoker辅助器安装包(透视)wepoker辅助器安装包,教程手筋(竟然有挂)-哔哩哔...
透视教你!wepoker透视有... 透视教你!wepoker透视有用吗(透视)智星菠萝透视,教程诀窍(有挂攻略)-哔哩哔哩1、首先打开w...
透视透视!pokerworld... 透视透视!pokerworld修改器(透视)xpoker辅助神器,教程经验(有挂透明挂)-哔哩哔哩1...
透视科普!epoker免费透视... 透视科普!epoker免费透视脚本(透视)wepoker怎么看牌型,教程要领(有挂头条)-哔哩哔哩1...
透视揭露!wepoker透视脚... 透视揭露!wepoker透视脚本免费app(透视)wpk私人局辅助是真的吗,教程手册(有挂分析)-哔...
透视曝光!aapoker辅助怎... 透视曝光!aapoker辅助怎么用(透视)wpk插件辅助,教程攻略(有挂讲解)-哔哩哔哩1、打开软件...
透视解密!xpoker透视辅助... 透视解密!xpoker透视辅助(透视)fishpoker透视底牌,教程操作(真是有挂)-哔哩哔哩1、...
透视透视!聚星ai辅助工具收费... 透视透视!聚星ai辅助工具收费多少(透视)wepoker有透视吗,教程方式(有挂解密)-哔哩哔哩1、...
透视普及!如何判断wpk辅助软... 透视普及!如何判断wpk辅助软件的真假(透视)wepoker透视脚本免费使用视频,教程手册(有挂实锤...
透视辅助!aapoker透视怎... 透视辅助!aapoker透视怎么用(透视)德普之星透视辅助,教程方针(确实有挂)-哔哩哔哩1、每一步...