redis_config.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # !/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. @Project : lq-agent-api
  5. @File :redis_config.py
  6. @IDE :PyCharm
  7. @Author :
  8. @Date :2025/7/21 13:44
  9. '''
  10. from dataclasses import dataclass
  11. from urllib.parse import quote
  12. from foundation.infrastructure.config.config import config_handler
  13. @dataclass
  14. class RedisConfig:
  15. """Redis 连接配置"""
  16. url: str = "redis://127.0.0.1:6379"
  17. host: str = "127.0.0.1"
  18. port: int = 6379
  19. password: str = None
  20. db: int = 0
  21. max_connections: int = 50
  22. session_prefix: str = "session:"
  23. lock_prefix: str = "lock:"
  24. session_ttl: int = 3600 # 会话过期时间(秒)
  25. def _build_redis_url(host: str, port: int, password: str | None, db: int) -> str:
  26. if password:
  27. return f"redis://:{quote(password, safe='')}@{host}:{port}/{db}"
  28. return f"redis://{host}:{port}/{db}"
  29. def load_config_from_env() -> RedisConfig:
  30. """加载 Redis 配置,兼容 REDIS_URL 和 REDIS_HOST/PORT/PASSWORD/DB。"""
  31. host = config_handler.get("redis", "REDIS_HOST", "127.0.0.1")
  32. port = int(config_handler.get("redis", "REDIS_PORT", "6379"))
  33. password = config_handler.get("redis", "REDIS_PASSWORD", "") or None
  34. db = int(config_handler.get("redis", "REDIS_DB", "0"))
  35. redis_url = config_handler.get("redis", "REDIS_URL", "") or _build_redis_url(host, port, password, db)
  36. redis_config = RedisConfig(
  37. url=redis_url,
  38. host=host,
  39. port=port,
  40. password=password,
  41. db=db,
  42. max_connections=int(config_handler.get("redis", "REDIS_MAX_CONNECTIONS", "50"))
  43. )
  44. return redis_config