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