[英]How to share database connection between workers using FastAPI + uvicorn?
I'm trying to create an app using FastAPI + uvicorn.我正在尝试使用 FastAPI + uvicorn 创建一个应用程序。
This app must be able to handle simultaneous connections.此应用程序必须能够处理同时连接。 I cannot guarantee that all the code can be executed in a async/await way.我不能保证所有代码都可以异步/等待方式执行。
Then, I thought to use the --workers X
options from uvicorn to handle simultaneous connections, but I need to share the same database connection among all the workers.然后,我想使用 uvicorn 的 --workers --workers X
选项来处理同时连接,但我需要在所有工作人员之间共享相同的数据库连接。
I tried the following example:我尝试了以下示例:
import time
from pymongo.database import Database
from fastapi import Depends, FastAPI
from dynaconf import settings
from pymongo import MongoClient
print("-------> Creating a new MongoDB connection")
db_conn = MongoClient(settings.MONGODB_URI)
db = db_conn.get_database('mydb')
app = FastAPI()
def get_db():
return db
@app.get("/{id}")
async def main(id: str, db: Database = Depends(get_db)):
print("Recebido id: " + id)
time.sleep(10)
return { 'id': id }
$uvicorn main:app --workers 2
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started parent process [24730]
-------> Creating a new MongoDB connection
-------> Creating a new MongoDB connection
INFO: Started server process [24733]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Started server process [24732]
INFO: Waiting for application startup.
INFO: Application startup complete.
But I'm getting two mongodb connections.但我得到了两个 mongodb 连接。
How can I share the MongoDB connection and avoid creating a connection each single worker?如何共享 MongoDB 连接并避免为每个工作人员创建连接?
You must not share the connection, as it's stateful.您不能共享连接,因为它是有状态的。 Two or more processes couldn't be able to use a single socket connection successfully.两个或多个进程无法成功使用单个套接字连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.