feat: 初始化考培练系统项目
- 从服务器拉取完整代码 - 按框架规范整理项目结构 - 配置 Drone CI 测试环境部署 - 包含后端(FastAPI)、前端(Vue3)、管理端 技术栈: Vue3 + TypeScript + FastAPI + MySQL
This commit is contained in:
44
backend/app/core/redis.py
Normal file
44
backend/app/core/redis.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
Redis连接管理
|
||||
"""
|
||||
from typing import Optional
|
||||
from redis import asyncio as aioredis
|
||||
from app.core.config import settings
|
||||
from app.core.logger import logger
|
||||
|
||||
# 全局Redis连接实例
|
||||
redis_client: Optional[aioredis.Redis] = None
|
||||
|
||||
|
||||
async def init_redis() -> aioredis.Redis:
|
||||
"""初始化Redis连接"""
|
||||
global redis_client
|
||||
|
||||
try:
|
||||
redis_client = await aioredis.from_url(
|
||||
settings.REDIS_URL, encoding="utf-8", decode_responses=True
|
||||
)
|
||||
# 测试连接
|
||||
await redis_client.ping()
|
||||
logger.info("Redis连接成功", url=settings.REDIS_URL)
|
||||
return redis_client
|
||||
except Exception as e:
|
||||
logger.error("Redis连接失败", error=str(e), url=settings.REDIS_URL)
|
||||
raise
|
||||
|
||||
|
||||
async def close_redis():
|
||||
"""关闭Redis连接"""
|
||||
global redis_client
|
||||
|
||||
if redis_client:
|
||||
await redis_client.close()
|
||||
logger.info("Redis连接已关闭")
|
||||
redis_client = None
|
||||
|
||||
|
||||
def get_redis_client() -> aioredis.Redis:
|
||||
"""获取Redis客户端实例"""
|
||||
if not redis_client:
|
||||
raise RuntimeError("Redis client not initialized")
|
||||
return redis_client
|
||||
Reference in New Issue
Block a user