54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
|
|
import redis
|
|||
|
|
from loguru import logger
|
|||
|
|
from config.settings import REDIS_CONFIG
|
|||
|
|
|
|||
|
|
class RedisClient:
|
|||
|
|
"""Redis客户端管理器"""
|
|||
|
|
|
|||
|
|
_instance = None
|
|||
|
|
|
|||
|
|
def __new__(cls):
|
|||
|
|
if cls._instance is None:
|
|||
|
|
cls._instance = super().__new__(cls)
|
|||
|
|
cls._instance._initialized = False
|
|||
|
|
return cls._instance
|
|||
|
|
|
|||
|
|
def __init__(self):
|
|||
|
|
if not self._initialized:
|
|||
|
|
self._pool = None
|
|||
|
|
self._client = None
|
|||
|
|
self._initialized = True
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def client(self):
|
|||
|
|
"""获取Redis客户端(懒加载)"""
|
|||
|
|
if self._client is None:
|
|||
|
|
self._init_connection_pool()
|
|||
|
|
return self._client
|
|||
|
|
|
|||
|
|
def _init_connection_pool(self):
|
|||
|
|
"""初始化连接池"""
|
|||
|
|
try:
|
|||
|
|
self._pool = redis.ConnectionPool(
|
|||
|
|
host=REDIS_CONFIG['host'],
|
|||
|
|
port=REDIS_CONFIG['port'],
|
|||
|
|
db=REDIS_CONFIG['db'],
|
|||
|
|
decode_responses=REDIS_CONFIG['decode_responses'],
|
|||
|
|
max_connections=REDIS_CONFIG['max_connections'],
|
|||
|
|
socket_keepalive=True
|
|||
|
|
)
|
|||
|
|
self._client = redis.Redis(connection_pool=self._pool)
|
|||
|
|
|
|||
|
|
# 测试连接
|
|||
|
|
self._client.ping()
|
|||
|
|
logger.info("Redis连接池初始化成功")
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
logger.error(f"Redis连接失败: {e}")
|
|||
|
|
raise
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
"""关闭连接池"""
|
|||
|
|
if self._pool:
|
|||
|
|
self._pool.disconnect()
|
|||
|
|
logger.info("Redis连接池已关闭")
|