feat: 完成redis的初始化动作
This commit is contained in:
@@ -25,6 +25,11 @@ class Settings(BaseSettings):
|
||||
llama_index_collection: str = Field(..., env="LLAMA_INDEX_COLLECTION")
|
||||
llama_index_dimension: str = Field(..., env="LLAMA_INDEX_DIMENSION")
|
||||
|
||||
redis_host: str = Field(..., env="REDIS_HOST")
|
||||
redis_port: str = Field(..., env="REDIS_PORT")
|
||||
redis_password: str = Field(..., env="REDIS_PASSWORD")
|
||||
redis_db: str = Field(..., env="REDIS_DB")
|
||||
|
||||
llm_key_local: str = Field(..., env="LLM_KEY_LOCAL")
|
||||
llm_key_huoshan: str = Field(..., env="LLM_KEY_HUOSHAN")
|
||||
llm_key_bailian: str = Field(..., env="LLM_KEY_BAILIAN")
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.utils.redis_utils import RedisClientDep
|
||||
|
||||
|
||||
def add_redis_route(app: FastAPI):
|
||||
@app.post("/redis_set/{key}")
|
||||
async def redis_set(key: str, value: dict, redis_client: RedisClientDep):
|
||||
await redis_client.hset(key, mapping=value)
|
||||
return {"result": "success"}
|
||||
|
||||
@app.get("/redis_get/{key}")
|
||||
async def redis_get(key: str, redis_client: RedisClientDep):
|
||||
return {"result": await redis_client.hgetall(key)}
|
||||
+7
-2
@@ -11,6 +11,7 @@ from app.middlewares.app_middlewares import add_app_middlewares
|
||||
from app.utils.db_utils import check_database_connection
|
||||
from app.utils.milvus_utils import milvus_service
|
||||
from app.utils.postgres_checkpointer import check_postgres_connection, close_postgres_connection
|
||||
from app.utils.redis_utils import redis_utils
|
||||
|
||||
|
||||
def create_app():
|
||||
@@ -21,12 +22,16 @@ def create_app():
|
||||
asyncio.create_task(check_database_connection()),
|
||||
asyncio.create_task(check_postgres_connection()),
|
||||
asyncio.create_task(milvus_service.check_milvus_connection()),
|
||||
asyncio.create_task(redis_utils.check_redis_connection()),
|
||||
)
|
||||
async_engine = async_results[0]
|
||||
yield
|
||||
print("lifespan:销毁阶段")
|
||||
await async_engine.dispose()
|
||||
await close_postgres_connection()
|
||||
await asyncio.gather(
|
||||
async_engine.dispose(),
|
||||
close_postgres_connection(),
|
||||
redis_utils.close_redis_connection()
|
||||
)
|
||||
|
||||
app = FastAPI(
|
||||
docs_url=None, # 禁用默认 Swagger
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.controller.add_langgraph_approve_route import add_langgraph_approve_rou
|
||||
from app.controller.add_langgraph_chat_route import add_langgraph_chat_route
|
||||
from app.controller.add_langgraph_route import add_langgraph_route
|
||||
from app.controller.add_lg_approve_route import add_lg_approve_route
|
||||
from app.controller.add_redis_route import add_redis_route
|
||||
from app.controller.add_reimburse_route import add_reimburse_route
|
||||
from app.controller.add_sqlmodel_route import add_sqlmodel_route
|
||||
from app.controller.add_user_route import add_user_route
|
||||
@@ -72,6 +73,7 @@ add_hotel_route(app)
|
||||
add_file_route(app)
|
||||
add_knowledge_route(app)
|
||||
add_api_route(app)
|
||||
add_redis_route(app)
|
||||
|
||||
|
||||
@app.get("/get_env")
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Annotated
|
||||
|
||||
import redis.asyncio as redis
|
||||
from fastapi import Depends
|
||||
|
||||
from app.config.env import env
|
||||
|
||||
|
||||
class RedisUtils():
|
||||
def __init__(self):
|
||||
self.redis_pool = None
|
||||
|
||||
# 检查 Redis 连接,先创建连接池管理对象
|
||||
async def check_redis_connection(self):
|
||||
self.redis_pool = redis.ConnectionPool(
|
||||
host=env.redis_host,
|
||||
port=env.redis_port,
|
||||
password=env.redis_password,
|
||||
db=env.redis_db,
|
||||
encoding="utf-8",
|
||||
decode_responses=True
|
||||
)
|
||||
# 立即对redis做一次读写测试
|
||||
async with self.get_redis_connection() as redis_client:
|
||||
try:
|
||||
await redis_client.ping()
|
||||
random_id = str(uuid.uuid4())
|
||||
await redis_client.set("__init__setup__", random_id)
|
||||
cache_random_id = await redis_client.get("__init__setup__")
|
||||
if cache_random_id != random_id:
|
||||
raise Exception("Redis 连接失败,读写测试不一致")
|
||||
print("✅ Redis connection successful:", f"redis://{env.redis_password}@${env.redis_host}:{env.redis_port}/{env.redis_db}")
|
||||
except Exception as e:
|
||||
print(f"❌ Database connection failed")
|
||||
raise e
|
||||
|
||||
# 获取一个Redis连接客户端
|
||||
@asynccontextmanager
|
||||
async def get_redis_connection(self):
|
||||
if not self.redis_pool:
|
||||
raise Exception("Redis 连接池未初始化")
|
||||
redis_client = redis.Redis(connection_pool=self.redis_pool)
|
||||
try:
|
||||
yield redis_client
|
||||
finally:
|
||||
await redis_client.close()
|
||||
|
||||
# 清理Redis连接池
|
||||
async def close_redis_connection(self):
|
||||
if self.redis_pool:
|
||||
await self.redis_pool.disconnect()
|
||||
|
||||
|
||||
redis_utils = RedisUtils()
|
||||
|
||||
|
||||
# 作用:用于在接口中注入得到会话实例对象session,在接口执行完毕之后,自动执行close动作关闭会话
|
||||
async def get_redis_client() -> redis.Redis:
|
||||
async with redis_utils.get_redis_connection() as redis_client:
|
||||
yield redis_client
|
||||
|
||||
|
||||
RedisClientDep = Annotated[redis.Redis, Depends(get_redis_client)]
|
||||
Reference in New Issue
Block a user