From e24cb69becc599b65b9d9318d92375f7763cd97b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A5=BF=E7=93=9C=C2=B0?= Date: Tue, 26 May 2026 01:50:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BC=93=E5=AD=98=E9=A2=84?= =?UTF-8?q?=E7=83=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/main.py | 23 ++--------------------- backend/preheat.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 21 deletions(-) create mode 100644 backend/preheat.py diff --git a/backend/main.py b/backend/main.py index 4d24d702..5f5145ae 100644 --- a/backend/main.py +++ b/backend/main.py @@ -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) diff --git a/backend/preheat.py b/backend/preheat.py new file mode 100644 index 00000000..a839d23a --- /dev/null +++ b/backend/preheat.py @@ -0,0 +1,15 @@ +import time + +from api.core.RedisPreheat import preheat_redis_cache + + +def main(): + start = time.perf_counter() + print('Redis 缓存预热开始...') + warmed_keys = preheat_redis_cache() + duration = time.perf_counter() - start + print(f'Redis 缓存预热完成: {len(warmed_keys)} keys, {duration:.2f}s') + + +if __name__ == '__main__': + main()