redis.py 676 B

12345678910111213141516171819202122232425262728293031323334
  1. """
  2. Redis连接管理
  3. """
  4. import redis.asyncio as aioredis
  5. from redis.asyncio import Redis
  6. from app.core.config import settings
  7. from typing import Optional
  8. # Redis连接池
  9. redis_pool: Optional[Redis] = None
  10. async def get_redis() -> Redis:
  11. """
  12. 获取Redis连接
  13. """
  14. global redis_pool
  15. if redis_pool is None:
  16. redis_pool = await aioredis.from_url(
  17. settings.REDIS_URL,
  18. encoding="utf-8",
  19. decode_responses=True,
  20. max_connections=50,
  21. )
  22. return redis_pool
  23. async def close_redis():
  24. """
  25. 关闭Redis连接
  26. """
  27. global redis_pool
  28. if redis_pool:
  29. await redis_pool.close()