baodan/api/insurance/db/redis.py

51 lines
1.3 KiB
Python
Raw Normal View History

"""Redis 初始化模块
独立部署时使用的 Redis 初始化不依赖 Dify 扩展
"""
import os
2026-07-12 14:17:18 +08:00
import logging
from flask import Flask
import redis
2026-07-12 14:17:18 +08:00
logger = logging.getLogger(__name__)
# Redis 客户端实例
redis_client = None
def init_redis(app: Flask) -> None:
2026-07-12 14:17:18 +08:00
"""初始化 Redis 连接(使用连接池 + 自动重连)。"""
global redis_client
redis_url = app.config.get('REDIS_URL', 'redis://localhost:6379/0')
try:
2026-07-12 14:17:18 +08:00
# 使用连接池,配置自动重连和健康检查
pool = redis.ConnectionPool.from_url(
redis_url,
decode_responses=True,
max_connections=20,
retry_on_timeout=True,
health_check_interval=30,
)
redis_client = redis.Redis(connection_pool=pool)
# 测试连接
redis_client.ping()
2026-07-12 14:17:18 +08:00
logger.info(f"Redis 连接成功: {redis_url}")
except Exception as e:
2026-07-12 14:17:18 +08:00
logger.warning(f"Redis 连接失败: {e}")
redis_client = None
def get_redis():
2026-07-12 14:17:18 +08:00
"""获取 Redis 客户端实例(自动重连)。"""
global redis_client
# 如果之前连接失败,尝试重新连接
if redis_client is None:
try:
from flask import current_app
init_redis(current_app)
except Exception:
pass
return redis_client