Files
aiData/Util/RedisKit.py
HuangHai 34501faafb 'commit'
2026-01-20 08:09:13 +08:00

114 lines
3.6 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.

import asyncio
import logging
import os
import uuid
import json
import redis
from Config.Config import REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD, REDIS_DECODE_RESPONSES
# 创建logger实例
logger = logging.getLogger(__name__)
class RedisKit:
"""
异步Redis工具类提供所有Redis操作的异步实现
单例模式确保全局只有一个Redis连接池
"""
_instance = None
_lock = asyncio.Lock()
_redis_pool = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
async def _ensure_pool(self):
"""
确保Redis连接池已创建
"""
if RedisKit._redis_pool is None:
async with RedisKit._lock:
if RedisKit._redis_pool is None:
try:
# 创建同步Redis连接池
sync_pool = redis.ConnectionPool(
host=REDIS_HOST,
port=REDIS_PORT,
db=REDIS_DB,
password=REDIS_PASSWORD,
decode_responses=REDIS_DECODE_RESPONSES
)
# 创建Redis连接实例
RedisKit._redis_pool = redis.Redis(
connection_pool=sync_pool,
encoding='utf-8',
decode_responses=REDIS_DECODE_RESPONSES
)
# 测试连接
await asyncio.to_thread(RedisKit._redis_pool.ping)
logger.info("Redis连接池创建成功")
except Exception as e:
logger.error(f"Redis连接池创建失败: {e}")
raise
async def get_connection(self):
"""
获取Redis连接实例
Returns:
redis.Redis: Redis连接实例
"""
await self._ensure_pool()
return RedisKit._redis_pool
async def get_data(self, key):
"""
异步从Redis中获取数据
Args:
key (str): Redis键名
Returns:
any: Redis中存储的值如果键不存在则返回None
"""
try:
await self._ensure_pool()
return await asyncio.to_thread(RedisKit._redis_pool.get, key)
except Exception as e:
logger.error(f"从Redis获取数据失败(key={key}): {e}")
return None
async def exists(self, key):
"""
异步检查Redis键是否存在
Args:
key (str): Redis键名
Returns:
bool: 键存在返回True不存在或失败返回False
"""
try:
await self._ensure_pool()
result = await asyncio.to_thread(RedisKit._redis_pool.exists, key)
return bool(result)
except Exception as e:
logger.error(f"检查Redis键是否存在失败(key={key}): {e}")
return False
async def set_data(self, key, value, expire=None):
try:
await self._ensure_pool()
if expire:
await asyncio.to_thread(RedisKit._redis_pool.set, key, value, ex=expire)
else:
await asyncio.to_thread(RedisKit._redis_pool.set, key, value)
return True
except Exception as e:
logger.error(f"保存数据到Redis失败(key={key}): {e}")
return False
# ȫ<><C8AB>ʵ<EFBFBD><CAB5>
redisKit = RedisKit()