添加缓存预热

This commit is contained in:
2026-05-26 01:50:30 +08:00
parent dad0af30de
commit e24cb69bec
2 changed files with 17 additions and 21 deletions
+2 -21
View File
@@ -1,5 +1,4 @@
import asyncio
from contextlib import asynccontextmanager, suppress
from contextlib import asynccontextmanager
import os
import time
from multiprocessing import freeze_support
@@ -8,34 +7,16 @@ import uvicorn
from fastapi import FastAPI
from api.core import Exceptions, Gzip, Middleware
from api.core.RedisPreheat import preheat_redis_cache
from api.main import api_router
from config.main import config
async def _run_redis_preheat_background():
print('Redis 缓存预热中(后台)...')
start = time.perf_counter()
try:
warmed_keys = await asyncio.to_thread(preheat_redis_cache)
duration = time.perf_counter() - start
print(f'Redis 缓存预热完成: {len(warmed_keys)} keys, {duration:.2f}s')
except Exception as exc:
print(f'Redis 缓存预热失败: {exc}')
@asynccontextmanager
async def lifespan(app: FastAPI):
async def lifespan(_: FastAPI):
print('dcalc is starting...')
print('Application starting...')
app.state.redis_preheat_task = asyncio.create_task(_run_redis_preheat_background())
print('Application startup complete.')
yield
preheat_task = getattr(app.state, 'redis_preheat_task', None)
if preheat_task and not preheat_task.done():
preheat_task.cancel()
with suppress(asyncio.CancelledError):
await preheat_task
application = FastAPI(docs_url='/doc', redoc_url=None, lifespan=lifespan)