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

相关内容

热门资讯

查到实测!hhpoker有没有... 查到实测!hhpoker有没有外挂,wepoker私局辅助,爆料教程(有挂透视)关于hhpoker有...
透视挂"hhpoke... 透视挂"hhpoker俱乐部是干嘛的"详细辅助必赢方法(起初真的是有挂)准备好在hhpoker俱乐部...
科技通报!cloudpoker... 1、科技通报!cloudpoker怎么开挂,wpk免费辅助,教你攻略(有挂神器)。2、cloudpo...
透视透视挂"hhpo... 透视透视挂"hhpoker辅助靠谱吗"详细辅助技巧教程(原生有挂);最新版2024是一款经典耐玩的益...
必备攻略!wepoker买钻石... 必备攻略!wepoker买钻石有用吗,约局吧辅助器,透明教程(有挂教程);实战中需综合运用上述技巧,...
透视规律"wejok... 《透视规律"wejoker手机版透视脚本"详细辅助2025新版教程(起初真的是有挂)》 wejoke...
科技介绍!wepoker国外版... 1、科技介绍!wepoker国外版透视,约局吧开挂神器是真的吗,细节揭秘(有挂神器)(UU poke...
透视安装"wepok... 透视安装"wepokerplus开挂"详细辅助科技教程(最初真的是有挂);《WPK辅助透视》‌:支持...
玩家攻略!hhpoker真能买... 玩家攻略!hhpoker真能买到挂吗,wepoker私人定制透视,攻略教程(有挂攻略);实战中需综合...
透视模拟器"约局吧辅... 透视模拟器"约局吧辅助器"详细辅助详细教程(一向真的有挂);1.约局吧辅助器 ai辅助创建新账号,点...