title: 驾驭FastAPI多数据库:从读写分离到跨库事务的艺术
date: 2025/05/16 00:58:24
updated: 2025/05/16 00:58:24
author: cmdragon
excerpt:
在微服务架构中,FastAPI 多数据库配置管理通过独立数据存储实现隔离性、扩展性和性能优化。配置主从数据库时,使用 SQLAlchemy 创建异步引擎和会话工厂,并通过中间件实现动态数据库路由,实现读写分离。跨库事务处理采用 Saga 事务模式,确保分布式事务的一致性。以电商订单系统为例,展示了如何在 PostgreSQL、MongoDB 和 MySQL 之间进行跨库操作,并通过补偿机制处理事务失败。常见报错解决方案包括精确查询条件、正确管理会话和处理事务回滚。
categories:
tags:
扫描二维码
关注或者微信搜一搜:编程智域 前端至全栈交流与成长
探索数千个预构建的 AI 应用,开启你的下一个伟大创意:https://tools.cmdragon.cn/
在微服务架构中,每个服务通常需要独立的数据存储。就像大型图书馆需要将不同学科的书籍分馆存放一样,电商系统可能将用户数据、订单数据、商品数据分别存储在不同数据库。这种架构带来三个核心需求:
以下示例展示如何在FastAPI中配置主从数据库:
# database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
# 主数据库配置(写操作)
MASTER_DATABASE_URL = "postgresql+asyncpg://user:password@master-host/dbname"
master_engine = create_async_engine(MASTER_DATABASE_URL, pool_size=10)
# 从数据库配置(读操作)
REPLICA_DATABASE_URL = "postgresql+asyncpg://user:password@replica-host/dbname"
replica_engine = create_async_engine(REPLICA_DATABASE_URL, pool_size=20)
# 创建会话工厂
MasterSession = sessionmaker(master_engine, class_=AsyncSession, expire_on_commit=False)
ReplicaSession = sessionmaker(replica_engine, class_=AsyncSession, expire_on_commit=False)
关键配置参数说明:
pool_size
:连接池大小,根据服务负载调整max_overflow
:允许超出连接池数量的临时连接pool_timeout
:获取连接的超时时间(秒)通过中间件实现读写分离:
# dependencies.py
from fastapi import Request, Depends
from database import MasterSession, ReplicaSession
async def get_db(request: Request):
"""智能路由数据库连接"""
# 写操作路由到主库
if request.method in ['POST', 'PUT', 'DELETE']:
db = MasterSession()
else: # 读操作使用从库
db = ReplicaSession()
try:
yield db
finally:
await db.close()
# 在路由中使用
@app.post("/orders")
async def create_order(
order: OrderSchema,
db: AsyncSession = Depends(get_db)
):
# 业务逻辑
当订单服务需要同时更新订单库和扣减库存库时,传统ACID事务不再适用。这就像需要同时在两个不同银行账户之间转账,必须保证要么全部成功,要么全部失败。
# services/transaction_coordinator.py
from typing import List
from fastapi import HTTPException
class SagaCoordinator:
def __init__(self):
self.compensation_actions = []
async def execute_transaction(self, steps: List[callable]):
"""执行Saga事务"""
try:
for step in steps:
await step()
except Exception as e:
await self.compensate()
raise HTTPException(500, "Transaction failed")
async def compensate(self):
"""补偿操作执行"""
for action in reversed(self.compensation_actions):
try:
await action()
except Exception as compen_e:
# 记录补偿失败日志
logger.error(f"Compensation failed: {compen_e}")
# 使用示例
async def create_order_transaction():
coordinator = SagaCoordinator()
async def deduct_inventory():
# 预留库存
coordinator.compensation_actions.append(restore_inventory)
async def create_order_record():
# 创建订单记录
coordinator.compensation_actions.append(delete_order_record)
await coordinator.execute_transaction([
deduct_inventory,
create_order_record
])
用户下单时需要同时操作:
# models.py
from pydantic import BaseModel
class OrderCreate(BaseModel):
user_id: int
product_id: str
quantity: int
# services/order_service.py
from sqlalchemy import text
from motor.motor_asyncio import AsyncIOMotorClient
class OrderService:
def __init__(self):
# 初始化各数据库连接
self.pg_pool = MasterSession
self.mongo_client = AsyncIOMotorClient(MONGO_URI)
self.mysql_pool = create_async_engine(MYSQL_URI)
async def create_order(self, order_data: OrderCreate):
"""创建订单事务"""
async with self.pg_pool() as pg_session,
self.mysql_pool.begin() as mysql_conn:
# 步骤1:扣减MySQL库存
mysql_update = text("""
UPDATE inventory
SET stock = stock - :quantity
WHERE product_id = :product_id
AND stock >= :quantity
""")
await mysql_conn.execute(
mysql_update,
product_id=order_data.product_id,
quantity=order_data.quantity
)
# 步骤2:创建PostgreSQL订单
pg_insert = text("""
INSERT INTO orders (user_id, product_id, quantity)
VALUES (:user_id, :product_id, :quantity)
""")
await pg_session.execute(pg_insert, order_data.dict())
# 步骤3:更新MongoDB用户行为
mongo_db = self.mongo_client.user_behavior
await mongo_db.events.insert_one({
"user_id": order_data.user_id,
"event_type": "order_created",
"timestamp": datetime.now()
})
# 提交PostgreSQL事务
await pg_session.commit()
问题1: 当使用多个数据库时,如何保证跨库查询的事务一致性?
A. 使用数据库自带的分布式事务功能
B. 采用最终一致性模式配合补偿机制
C. 强制所有操作使用同个数据库
D. 增加重试机制自动处理失败
答案: B
解析: 在微服务架构中,不同服务通常使用不同数据库实例,传统ACID事务难以实施。采用Saga模式等最终一致性方案,配合补偿事务(如订单取消时的库存回补),是更可行的解决方案。
错误1: MultipleResultsFound: Multiple rows were found when one was required
原因: 查询语句返回了多个结果,但期望单个结果
解决:
.first()
代替.one()
错误2: InterfaceError: Connection already closed
原因: 数据库连接过早关闭
预防:
# 正确使用方式
async def get_db():
async with Session() as session:
yield session
错误3: DBAPIError: Can't reconnect until invalid transaction is rolled back
原因: 未正确处理事务回滚
解决:
async def safe_transaction():
async with session.begin():
try:
# 业务操作
await session.commit()
except:
await session.rollback()
raise
余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
,阅读完整的文章:驾驭FastAPI多数据库:从读写分离到跨库事务的艺术 | cmdragon's Blog
参与评论
手机查看
返回顶部