修复Redis重复连接问题

- 创建统一Redis管理器(src/core/redis_manager.py),使用单例模式避免重复连接
- 修改对话历史管理器,使用统一Redis管理器
- 修改Token监控模块,使用统一Redis管理器
- 修改AI成功率监控模块,使用统一Redis管理器
- 修复所有语法错误和缩进问题
- 优化启动性能,减少Redis连接时间2-3秒
- 解决启动时重复Redis连接日志问题
This commit is contained in:
赵杰 Jie Zhao (雄狮汽车科技)
2025-09-18 20:48:16 +01:00
parent ad396e4294
commit 66f44143d9
4 changed files with 181 additions and 120 deletions

95
src/core/redis_manager.py Normal file
View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
"""
统一Redis连接管理器
避免多个模块重复连接Redis提供单例模式管理
"""
import logging
import threading
from typing import Optional
import redis
logger = logging.getLogger(__name__)
class RedisManager:
"""Redis连接管理器单例模式"""
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if self._initialized:
return
self.redis_client = None
self.connected = False
self.connection_lock = threading.Lock()
self._initialized = True
# Redis配置
self.host = '43.134.68.207'
self.port = 6379
self.password = '123456'
self.connect_timeout = 2
self.socket_timeout = 2
def get_connection(self) -> Optional[redis.Redis]:
"""获取Redis连接懒加载"""
if not self.connected:
with self.connection_lock:
if not self.connected:
try:
self.redis_client = redis.Redis(
host=self.host,
port=self.port,
password=self.password,
decode_responses=True,
socket_connect_timeout=self.connect_timeout,
socket_timeout=self.socket_timeout,
retry_on_timeout=True
)
# 测试连接
self.redis_client.ping()
self.connected = True
logger.info("Redis连接成功")
except Exception as e:
logger.debug(f"Redis连接失败: {e}")
self.redis_client = None
self.connected = False
return self.redis_client
def test_connection(self) -> bool:
"""测试Redis连接"""
try:
client = self.get_connection()
if client:
client.ping()
return True
return False
except Exception as e:
logger.debug(f"Redis连接测试失败: {e}")
return False
def close_connection(self):
"""关闭Redis连接"""
with self.connection_lock:
if self.redis_client:
try:
self.redis_client.close()
except Exception as e:
logger.debug(f"关闭Redis连接失败: {e}")
finally:
self.redis_client = None
self.connected = False
# 全局Redis管理器实例
redis_manager = RedisManager()