async_redis_client.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import redis.asyncio as aioredis
  2. from core.utils.log.logger_manager import LoggerManager
  3. class RedisManager:
  4. _pool = None
  5. logger = LoggerManager.get_logger()
  6. @classmethod
  7. async def init(
  8. cls,
  9. redis_url: str = "",
  10. max_connections: int = 20,
  11. encoding: str = "utf-8",
  12. decode_responses: bool = True
  13. ):
  14. """
  15. 初始化 Redis 异步连接池,保证进程级单例。
  16. """
  17. if cls._pool is None:
  18. try:
  19. cls._pool = await aioredis.from_url(
  20. redis_url,
  21. max_connections=max_connections,
  22. encoding=encoding,
  23. decode_responses=decode_responses,
  24. retry_on_timeout=True,
  25. )
  26. cls.logger.debug(f"[RedisManager] Redis 连接池初始化成功: {redis_url}")
  27. except Exception as e:
  28. cls.logger.error(f"[RedisManager] Redis 连接池初始化失败: {e}")
  29. raise
  30. @classmethod
  31. def get_pool(cls):
  32. if cls._pool is None:
  33. raise Exception("[RedisManager] 未初始化,请先执行 RedisManager.init()")
  34. return cls._pool
  35. @classmethod
  36. async def close(cls):
  37. """
  38. 关闭连接池(在优雅退出时调用)
  39. """
  40. if cls._pool:
  41. await cls._pool.close()
  42. cls.logger.debug("[RedisManager] Redis 连接池已关闭")