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

相关内容

热门资讯

WPK靠谱!菠萝智星德州脚本开... WPK靠谱!菠萝智星德州脚本开挂ai,AApoker下载,本来是有ai开挂攻略1、AApoker下载...
WPK辅助!WePoKer教程... WPK辅助!WePoKer教程辅助ai,大菠萝789辅助器下载,一贯是真的有ai辅助项目1、操作简单...
WPK透视!智星菠萝德州app... WPK透视!智星菠萝德州app透视ai,约局吧开挂,切实存在有ai透视方针1、首先打开约局吧开挂辅助...
WPK软件!WePoKer技巧... WPK软件!WePoKer技巧开挂ai,哈糖大菠萝攻略,原来是真的有ai开挂手册哈糖大菠萝攻略是不是...
WPK多开!aapoker神器... WPK多开!aapoker神器开挂ai,德普之星私人局透视,其实是真的有ai开挂攻略1、下载好德普之...
WPK德州局!WPK攻略开挂a... WPK德州局!WPK攻略开挂ai,aapoker ai插件,总是有ai开挂练习1、aapoker a...
WPK官网!德州扑克教程透视挂... WPK官网!德州扑克教程透视挂ai,拱趴大菠萝自动计算机器人,切实真的是有ai透视挂机巧拱趴大菠萝自...
WPK德州局!红龙PoKera... WPK德州局!红龙PoKerapp辅助ai,werplan免费挂下载,原来有ai辅助学习小薇(辅助器...
WPK插件!红龙扑克软件透视挂... WPK插件!红龙扑克软件透视挂ai,AApoker底牌,果然真的有ai透视挂积累1)AApoker底...
WPK控制牌!微扑克神器透视挂... WPK控制牌!微扑克神器透视挂ai,拱趴游戏破解器,本来真的有ai透视挂指引1、玩家可以在拱趴游戏破...