from typing import Optional from utils import logger from .base_cache import BaseCache from .memory_cache import MemoryCache from .redis_cache import RedisCache # 全局缓存实例(初始为MemoryCache占位) cache: Optional['BaseCache'] = None async def initialize_cache(): """异步初始化缓存实例,需在应用启动时调用""" global cache try: if cache: return # 创建Redis缓存实例 redis_cache = RedisCache() # 显式调用异步初始化 await redis_cache.initialize() cache = redis_cache if not cache.redis: logger.info('Redis缓存已禁用,使用内存缓存') cache = MemoryCache() else: logger.info('Redis缓存已启用') except Exception as e: logger.error(f'缓存初始化失败,使用内存缓存:{e}') cache = MemoryCache() finally: # 确保无论如何都有默认缓存实例 if cache is None: logger.warning('缓存实例最终为空,强制使用内存缓存') cache = MemoryCache() __all__ = ['cache', 'initialize_cache', 'BaseCache']