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() 来释放连接。这样可以确保每次只使用一个连接,并避免创建过多的连接。

相关内容

热门资讯

透视安装!aapoker脚本怎... 透视安装!aapoker脚本怎么用(透视)插件下载(都是有挂)aapoker脚本怎么用辅助器中分为三...
透视好牌!aapoker怎么拿... 透视好牌!aapoker怎么拿好牌(透视)辅助(确实是有挂)1、aapoker怎么拿好牌ai辅助优化...
透视讲解!aapoker怎么提... 透视讲解!aapoker怎么提高中牌率(透视)透视软件(确实真的有挂)1、许多玩家不知道aapoke...
透视规律!aapoker辅助怎... 透视规律!aapoker辅助怎么用(透视)透视脚本(果然有挂)暗藏猫腻,小编详细说明aapoker辅...
透视神器!aapoker辅助工... 透视神器!aapoker辅助工具安全吗(透视)透视软件(确实真的有挂);1、打开软件启动之后找到中间...
透视数据!aapoker安装包... 透视数据!aapoker安装包怎么使用(透视)辅助(原来是真的有挂)1、下载好aapoker安装包怎...
透视美元局!aapoker破解... 透视美元局!aapoker破解侠是真的吗(透视)透视脚本(好像真的是有挂);1、超多福利:超高返利,...
透视能赢!aapoker破解侠... 透视能赢!aapoker破解侠是真的吗(透视)辅助(原来存在有挂)1、金币登录送、破产送、升级送、活...
透视线上!aapoker怎么设... 透视线上!aapoker怎么设置提高好牌几率(透视)插件下载(好像是有挂);1、首先打开aapoke...
透视中牌率!aapoker怎么... 透视中牌率!aapoker怎么控制牌(透视)发牌逻辑(真是是有挂);1、aapoker怎么控制牌机器...