55 lines
1.3 KiB
Python
55 lines
1.3 KiB
Python
"""
|
|
backend/app/services/redis_client.py
|
|
|
|
用途:Redis 连接封装,供热点 FAQ 候选池等模块使用。
|
|
依赖:redis、Flask current_app/config。
|
|
逻辑:连接失败时返回 None,调用方降级处理,不阻断主业务。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
try:
|
|
import redis
|
|
except ImportError: # pragma: no cover
|
|
redis = None # type: ignore
|
|
|
|
|
|
_redis_client: Any = None
|
|
|
|
|
|
def get_redis_client():
|
|
"""
|
|
获取进程内 Redis 客户端单例。
|
|
核心逻辑:读取 REDIS_URL;未配置或连接失败时返回 None。
|
|
@returns redis.Redis 或 None
|
|
"""
|
|
global _redis_client
|
|
if redis is None:
|
|
return None
|
|
if _redis_client is not None:
|
|
return _redis_client
|
|
|
|
from flask import current_app
|
|
|
|
redis_url = None
|
|
if current_app:
|
|
redis_url = current_app.config.get('REDIS_URL')
|
|
if not redis_url:
|
|
return None
|
|
|
|
try:
|
|
client = redis.from_url(redis_url, decode_responses=True)
|
|
client.ping()
|
|
_redis_client = client
|
|
return _redis_client
|
|
except Exception:
|
|
_redis_client = None
|
|
return None
|
|
|
|
|
|
def reset_redis_client() -> None:
|
|
"""测试或配置变更时重置单例。"""
|
|
global _redis_client
|
|
_redis_client = None
|