refactor: 统一 Redis 连接管理,改用 RedisService
- App 启动时初始化 RedisService,关闭时释放连接 - Celery worker 通过 worker_process_init 钩子初始化 Redis - Agent 端点改用 RedisService 替代直接创建连接 - Celery task 改为 async def,使用统一连接 - 删除无用的 infra 模块和 core/http/models - 日志脱敏,不记录 Redis 密码 - 初始化失败时 fail-fast - 异常发布添加二级保护
This commit is contained in:
+29
-3
@@ -1,18 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from core.config.settings import config
|
||||
from core.http.models import HealthResponse
|
||||
from core.http.response import build_problem_details
|
||||
from core.logging import configure_logging, get_logger, log_service_banner
|
||||
from services.base.redis import redis_service
|
||||
from v1.router import router as mobile_router
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
|
||||
|
||||
configure_logging(config)
|
||||
|
||||
log_service_banner(
|
||||
@@ -20,7 +28,26 @@ log_service_banner(
|
||||
environment=config.runtime.environment,
|
||||
)
|
||||
|
||||
app = FastAPI()
|
||||
logger = get_logger("api.app")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
initialized = await redis_service.initialize()
|
||||
if not initialized:
|
||||
logger.error("Redis service failed to initialize, aborting startup")
|
||||
raise RuntimeError("Redis service initialization failed")
|
||||
logger.info(
|
||||
"Redis service initialized",
|
||||
host=config.redis.host,
|
||||
db=config.redis.db,
|
||||
)
|
||||
yield
|
||||
await redis_service.close()
|
||||
logger.info("Redis service closed")
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=config.cors.allow_origins,
|
||||
@@ -29,7 +56,6 @@ app.add_middleware(
|
||||
allow_headers=config.cors.allow_headers,
|
||||
)
|
||||
app.include_router(mobile_router)
|
||||
logger = get_logger("api.app")
|
||||
|
||||
logger.info(
|
||||
"Web application initialized",
|
||||
|
||||
Reference in New Issue
Block a user