Files
assist/src/core/redis_manager.py
赵杰 Jie Zhao (雄狮汽车科技) 4b4bd683d9 修复重复初始化问题 - 统一Redis连接管理
主要修复:
1. 创建统一Redis连接管理器 (src/core/redis_manager.py)
   - 单例模式管理所有Redis连接
   - 懒加载连接,避免重复初始化
   - 线程安全的连接管理

2. 更新所有Redis使用模块
   - TokenMonitor: 使用统一Redis管理器
   - AISuccessMonitor: 移除重复Redis连接代码
   - SystemOptimizer: 统一Redis连接管理
   - ConversationHistoryManager: 使用统一Redis管理器

3. 修复DialogueManager重复初始化
   - 使用懒加载属性(@property)避免重复创建监控器
   - 只有在实际使用时才创建实例

4. 优化启动性能
   - 避免重复的Redis连接创建
   - 消除重复的TSP助手初始化
   - 减少启动时的日志输出

技术改进:
- 单例模式Redis管理器
- 懒加载组件初始化
- 统一连接管理
- 线程安全设计

解决启动卡顿问题,提升系统响应速度
2025-09-18 19:57:35 +01:00

82 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
Redis连接管理器
统一管理所有Redis连接避免重复连接
"""
import redis
import logging
import threading
from typing import Optional
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.config = {
'host': '43.134.68.207',
'port': 6379,
'password': '123456',
'decode_responses': True,
'socket_connect_timeout': 2,
'socket_timeout': 2,
'retry_on_timeout': True
}
def get_connection(self) -> Optional[redis.Redis]:
"""获取Redis连接懒加载"""
with self.connection_lock:
if not self.connected:
try:
self.redis_client = redis.Redis(**self.config)
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 is_connected(self) -> bool:
"""检查Redis是否已连接"""
return self.connected and self.redis_client is not None
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()