__init__.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from typing import Optional
  2. from utils import logger
  3. from .base_cache import BaseCache
  4. from .memory_cache import MemoryCache
  5. from .redis_cache import RedisCache
  6. # 全局缓存实例(初始为MemoryCache占位)
  7. cache: Optional['BaseCache'] = None
  8. async def initialize_cache():
  9. """异步初始化缓存实例,需在应用启动时调用"""
  10. global cache
  11. try:
  12. if cache:
  13. return
  14. # 创建Redis缓存实例
  15. redis_cache = RedisCache()
  16. # 显式调用异步初始化
  17. await redis_cache.initialize()
  18. cache = redis_cache
  19. if not cache.redis:
  20. logger.info('Redis缓存已禁用,使用内存缓存')
  21. cache = MemoryCache()
  22. else:
  23. logger.info('Redis缓存已启用')
  24. except Exception as e:
  25. logger.error(f'缓存初始化失败,使用内存缓存:{e}')
  26. cache = MemoryCache()
  27. finally:
  28. # 确保无论如何都有默认缓存实例
  29. if cache is None:
  30. logger.warning('缓存实例最终为空,强制使用内存缓存')
  31. cache = MemoryCache()
  32. __all__ = ['cache', 'initialize_cache', 'BaseCache']