将rtsp集成到FastAPI声明周期
This commit is contained in:
16
src/app.py
16
src/app.py
@@ -28,6 +28,7 @@ from src.api.errors import (
|
||||
from src.config import settings
|
||||
from src.database.connection import init_database
|
||||
from src.database.connection import db_manager
|
||||
from src.rtsp.service import rtsp_server
|
||||
|
||||
|
||||
# 生命周期管理
|
||||
@@ -53,10 +54,25 @@ async def lifespan(app: FastAPI):
|
||||
else:
|
||||
print("❌ 数据库连接失败")
|
||||
|
||||
# 启动 RTSP 服务(如果启用)
|
||||
if settings.RTSP_ENABLED:
|
||||
print("📹 启动 RTSP 服务...")
|
||||
rtsp_server.start()
|
||||
# 将 RTSP 服务实例保存到应用状态
|
||||
app.state.rtsp_server = rtsp_server
|
||||
else:
|
||||
print("⚠️ RTSP 服务未启用")
|
||||
|
||||
yield
|
||||
|
||||
# 关闭时
|
||||
print("🛑 algorithm service stopped...")
|
||||
|
||||
# 停止 RTSP 服务
|
||||
if settings.RTSP_ENABLED:
|
||||
print("🛑 停止 RTSP 服务...")
|
||||
rtsp_server.stop()
|
||||
|
||||
db_manager.close()
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ from pydantic_core.core_schema import FieldValidationInfo
|
||||
class Settings(BaseSettings):
|
||||
"""应用配置类"""
|
||||
|
||||
RTSP_ENABLED: bool = True
|
||||
|
||||
# API配置
|
||||
API_V1_PREFIX: str = "/api/v1"
|
||||
PROJECT_NAME: str = "algorithm-service"
|
||||
|
||||
55
src/rtsp/service.py
Normal file
55
src/rtsp/service.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
RTSP 服务模块 - 简洁版本,直接使用原始服务
|
||||
"""
|
||||
|
||||
import threading
|
||||
from src.rtsp_service_ws_1217 import RTSPService
|
||||
|
||||
|
||||
class SimpleRTSPServer:
|
||||
"""RTSP 服务管理器 - 简洁包装器"""
|
||||
|
||||
def __init__(self):
|
||||
self.is_running = False
|
||||
self.service = None
|
||||
self.thread = None
|
||||
|
||||
def start(self):
|
||||
"""启动 RTSP 服务"""
|
||||
if self.is_running:
|
||||
return
|
||||
|
||||
print("🚀 启动 RTSP 服务...")
|
||||
|
||||
# 创建原始服务实例
|
||||
self.service = RTSPService(config_path="config.yaml")
|
||||
|
||||
# 在新线程中启动服务
|
||||
self.thread = threading.Thread(
|
||||
target=self.service.start,
|
||||
daemon=True
|
||||
)
|
||||
self.thread.start()
|
||||
|
||||
self.is_running = True
|
||||
print("✅ RTSP 服务启动完成")
|
||||
|
||||
def stop(self):
|
||||
"""停止 RTSP 服务"""
|
||||
if not self.is_running:
|
||||
return
|
||||
|
||||
print("🛑 停止 RTSP 服务...")
|
||||
|
||||
if self.service:
|
||||
self.service.stop()
|
||||
|
||||
if self.thread:
|
||||
self.thread.join(timeout=5.0)
|
||||
|
||||
self.is_running = False
|
||||
print("✅ RTSP 服务已停止")
|
||||
|
||||
|
||||
# 创建全局实例
|
||||
rtsp_server = SimpleRTSPServer()
|
||||
Reference in New Issue
Block a user