51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
"""Redis 初始化模块
|
|
|
|
独立部署时使用的 Redis 初始化,不依赖 Dify 扩展。
|
|
"""
|
|
import os
|
|
import logging
|
|
from flask import Flask
|
|
import redis
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Redis 客户端实例
|
|
redis_client = None
|
|
|
|
|
|
def init_redis(app: Flask) -> None:
|
|
"""初始化 Redis 连接(使用连接池 + 自动重连)。"""
|
|
global redis_client
|
|
|
|
redis_url = app.config.get('REDIS_URL', 'redis://localhost:6379/0')
|
|
|
|
try:
|
|
# 使用连接池,配置自动重连和健康检查
|
|
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()
|
|
logger.info(f"Redis 连接成功: {redis_url}")
|
|
except Exception as e:
|
|
logger.warning(f"Redis 连接失败: {e}")
|
|
redis_client = None
|
|
|
|
|
|
def get_redis():
|
|
"""获取 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
|