diff --git a/app/api/redis_test.py b/app/api/redis_test.py index be6363f..57ec850 100644 --- a/app/api/redis_test.py +++ b/app/api/redis_test.py @@ -1,8 +1,9 @@ -from fastapi import APIRouter -from app.core.redis import redis_client +import redis +from fastapi import APIRouter, Depends +from app.core.redis import redis_client, get_redis redis_test_router = APIRouter() @redis_test_router.get("/ping-redis") -async def ping_redis(): - return {"pong": await redis_client.ping()} +async def ping_redis(r: redis.Redis = Depends(get_redis)): + return {"pong": await r.ping()} diff --git a/app/core/redis.py b/app/core/redis.py index fc9601e..6fa01ee 100644 --- a/app/core/redis.py +++ b/app/core/redis.py @@ -9,7 +9,7 @@ async def init_redis(): global redis_client if redis_client is None: redis_client = await redis.Redis( - host="localhost", + host="127.0.0.1", port=6379, decode_responses=True, # 返回 str 而不是 Bytes ) @@ -26,5 +26,7 @@ async def close_redis(): # FastAPI 依赖注入用的获取方法 async def get_redis() -> AsyncGenerator[redis.Redis, None]: - assert redis_client is not None, "Redis 未初始化" + global redis_client + if redis_client is None: + await init_redis() # 懒加载,避免 NoneType yield redis_client \ No newline at end of file diff --git a/settings.py b/settings.py index 368e79b..a51f967 100644 --- a/settings.py +++ b/settings.py @@ -23,7 +23,7 @@ TORTOISE_ORM = { ONLINE_SETTINGS = { 'connections': { - 'default': 'mysql://root:@124.221.145.135:3306/test_db', + 'default': 'mysql://root:@127.0.0.1:3306/test_db', }, 'apps': { 'models': {