Download app/cache.py from binhugg2/api: direct link, hf CLI and curl.
- Browser
- Download file 4.98 kB
-
https://huggingface.co/spaces/binhugg2/api/resolve/main/app/cache.py
- Command line
-
hf download hf://spaces/binhugg2/api/app/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/binhugg2/api/resolve/main/app/cache.py
4.98 kB
| """ | |
| Redis 缓存工具模块 | |
| - 支持降级:Redis 不可用时自动退出缓存模式,不影响业务 | |
| - key 命名规范:binv:{namespace}:{具体参数hash} | |
| """ | |
| import hashlib | |
| import json | |
| import logging | |
| from typing import Any | |
| import redis.asyncio as aioredis | |
| from app.config import settings | |
| logger = logging.getLogger("cache") | |
| # 全局 Redis 连接池(懒加载) | |
| _redis: aioredis.Redis | None = None | |
| async def get_redis() -> aioredis.Redis | None: | |
| """获取 Redis 连接,连接失败返回 None(降级模式)""" | |
| global _redis | |
| if not settings.CACHE_ENABLED: | |
| return None | |
| if _redis is None: | |
| try: | |
| _redis = aioredis.from_url( | |
| settings.REDIS_URL, | |
| encoding="utf-8", | |
| decode_responses=True, | |
| socket_connect_timeout=2, | |
| socket_timeout=2, | |
| ) | |
| await _redis.ping() | |
| logger.info(f"Redis connected: {settings.REDIS_URL}") | |
| except Exception as e: | |
| logger.warning(f"Redis unavailable, cache disabled: {e}") | |
| _redis = None | |
| return _redis | |
| async def close_redis(): | |
| """关闭 Redis 连接(应用退出时调用)""" | |
| global _redis | |
| if _redis is not None: | |
| await _redis.aclose() | |
| _redis = None | |
| def _make_key(namespace: str, **kwargs) -> str: | |
| """生成缓存 key,参数超过 32 字符时用 md5 压缩""" | |
| param_str = "&".join(f"{k}={v}" for k, v in sorted(kwargs.items()) if v is not None) | |
| if len(param_str) > 32: | |
| param_str = hashlib.md5(param_str.encode()).hexdigest() | |
| return f"binv:{namespace}:{param_str}" | |
| async def cache_get(key: str) -> Any | None: | |
| """读取缓存,失败返回 None""" | |
| r = await get_redis() | |
| if r is None: | |
| return None | |
| try: | |
| raw = await r.get(key) | |
| return json.loads(raw) if raw else None | |
| except Exception as e: | |
| logger.debug(f"cache_get error [{key}]: {e}") | |
| return None | |
| async def cache_set(key: str, value: Any, ttl: int) -> None: | |
| """写入缓存,失败静默忽略""" | |
| r = await get_redis() | |
| if r is None: | |
| return | |
| try: | |
| await r.setex(key, ttl, json.dumps(value, ensure_ascii=False, default=str)) | |
| except Exception as e: | |
| logger.debug(f"cache_set error [{key}]: {e}") | |
| async def cache_delete(key: str) -> None: | |
| """删除单个缓存 key""" | |
| r = await get_redis() | |
| if r is None: | |
| return | |
| try: | |
| await r.delete(key) | |
| except Exception as e: | |
| logger.debug(f"cache_delete error [{key}]: {e}") | |
| async def cache_delete_pattern(pattern: str) -> int: | |
| """按 pattern 批量删除缓存(使用 SCAN 避免阻塞)""" | |
| r = await get_redis() | |
| if r is None: | |
| return 0 | |
| try: | |
| deleted = 0 | |
| async for key in r.scan_iter(match=pattern, count=100): | |
| await r.delete(key) | |
| deleted += 1 | |
| return deleted | |
| except Exception as e: | |
| logger.debug(f"cache_delete_pattern error [{pattern}]: {e}") | |
| return 0 | |
| # ── 业务层 Key 生成器 ────────────────────────────────────────────────────────── | |
| def vod_list_key(category_id: int | None, page: int, page_size: int) -> str: | |
| return _make_key("vod:list", category_id=category_id, page=page, page_size=page_size) | |
| def vod_search_key(keyword: str, category_id: int | None, page: int, page_size: int) -> str: | |
| return _make_key("vod:search", keyword=keyword, category_id=category_id, page=page, page_size=page_size) | |
| def vod_latest_key(page: int, page_size: int) -> str: | |
| return _make_key("vod:latest", page=page, page_size=page_size) | |
| def vod_recommended_key(page: int, page_size: int) -> str: | |
| return _make_key("vod:recommended", page=page, page_size=page_size) | |
| def vod_detail_key(vod_id: int) -> str: | |
| return _make_key("vod:detail", vod_id=vod_id) | |
| def category_tree_key() -> str: | |
| return "binv:category:tree" | |
| # ── 缓存失效辅助 ────────────────────────────────────────────────────────────── | |
| async def invalidate_vod_cache(vod_id: int | None = None) -> None: | |
| """影片数据变更时清除相关缓存""" | |
| if vod_id: | |
| await cache_delete(vod_detail_key(vod_id)) | |
| # 列表缓存全部清除(因为排序、数量都可能变化) | |
| await cache_delete_pattern("binv:vod:list:*") | |
| await cache_delete_pattern("binv:vod:search:*") | |
| await cache_delete_pattern("binv:vod:latest:*") | |
| await cache_delete_pattern("binv:vod:recommended:*") | |
| async def invalidate_category_cache() -> None: | |
| """分类变更时清除分类树缓存""" | |
| await cache_delete(category_tree_key()) | |
| # 分类变化也影响影片列表 | |
| await cache_delete_pattern("binv:vod:list:*") | |