database.py 701 B

123456789101112131415161718192021222324
  1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker, declarative_base
  3. from app.core.config import settings
  4. # SQLAlchemy 2.0 style
  5. engine = create_engine(
  6. settings.DATABASE_URI,
  7. pool_pre_ping=True,
  8. echo=False,
  9. pool_size=100, # 基础连接池大小(支持更高并发)
  10. max_overflow=200, # 允许溢出更多连接(最大300个并发连接)
  11. pool_recycle=3600 # 连接回收时间(1小时,防止MySQL连接超时)
  12. )
  13. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  14. Base = declarative_base()
  15. def get_db():
  16. db = SessionLocal()
  17. try:
  18. yield db
  19. finally:
  20. db.close()