redis_util.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from redis import asyncio as aioredis
  2. from core.settings import redis_settings
  3. class RedisUtil:
  4. """
  5. Redis相关方法
  6. """
  7. redis = None
  8. @classmethod
  9. async def create_redis_pool(cls) -> aioredis.Redis:
  10. """
  11. 应用启动时初始化redis连接
  12. :return: Redis连接对象
  13. """
  14. if not redis_settings.enable:
  15. return
  16. from utils import logger
  17. logger.info('开始连接redis...')
  18. redis = await aioredis.from_url(
  19. url=f'redis://{redis_settings.host}',
  20. port=redis_settings.port,
  21. username=redis_settings.username,
  22. password=redis_settings.password,
  23. db=redis_settings.database,
  24. encoding='utf-8',
  25. decode_responses=True,
  26. )
  27. try:
  28. connection = await redis.ping()
  29. if connection:
  30. logger.info('redis连接成功')
  31. else:
  32. logger.error('redis连接失败')
  33. cls.redis = redis
  34. except AuthenticationError as e:
  35. logger.error(f'redis用户名或密码错误,详细错误信息:{e}')
  36. except TimeoutError as e:
  37. logger.error(f'redis连接超时,详细错误信息:{e}')
  38. except RedisError as e:
  39. logger.error(f'redis连接错误,详细错误信息:{e}')
  40. @classmethod
  41. async def get_redis_pool(cls) -> aioredis.Redis:
  42. """
  43. 获取redis连接对象
  44. :return: Redis连接对象
  45. """
  46. if cls.redis is None:
  47. await cls.create_redis_pool()
  48. return cls.redis
  49. @classmethod
  50. async def close_redis_pool(cls):
  51. """
  52. 应用关闭时关闭redis连接
  53. :return:
  54. """
  55. from utils import logger
  56. if cls.redis is None:
  57. return
  58. try:
  59. await cls.redis.close()
  60. logger.info('关闭redis连接成功')
  61. except RuntimeError as e:
  62. logger.debug('尝试关闭Redis连接时事件循环已关闭,可能正常退出:%s', e)