You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.5 KiB

"""
Redis客户端模块
"""
import redis
import json
import logging
from typing import Optional, List, Any
from app.config import settings
logger = logging.getLogger(__name__)
class RedisClient:
"""Redis客户端"""
_instance: Optional['RedisClient'] = None
_client: Optional[redis.Redis] = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if self._client is None:
try:
self._client = redis.from_url(
settings.REDIS_URL,
decode_responses=True
)
logger.info("Redis连接成功")
except Exception as e:
logger.warning(f"Redis连接失败: {str(e)}")
self._client = None
def is_connected(self) -> bool:
"""检查Redis是否连接"""
if self._client is None:
return False
try:
self._client.ping()
return True
except:
return False
def get(self, key: str) -> Optional[Any]:
"""获取缓存"""
if not self.is_connected():
return None
try:
value = self._client.get(key)
if value:
return json.loads(value)
return None
except Exception as e:
logger.error(f"Redis获取失败: {str(e)}")
return None
def set(self, key: str, value: Any, expire: int = None) -> bool:
"""设置缓存"""
if not self.is_connected():
return False
try:
self._client.set(key, json.dumps(value), ex=expire)
return True
except Exception as e:
logger.error(f"Redis设置失败: {str(e)}")
return False
def delete(self, key: str) -> bool:
"""删除缓存"""
if not self.is_connected():
return False
try:
self._client.delete(key)
return True
except Exception as e:
logger.error(f"Redis删除失败: {str(e)}")
return False
def exists(self, key: str) -> bool:
"""检查键是否存在"""
if not self.is_connected():
return False
try:
return self._client.exists(key) > 0
except Exception as e:
logger.error(f"Redis检查失败: {str(e)}")
return False
redis_client = RedisClient()