From df99e3ac76b51ba444df65508cb3259ea23e562d Mon Sep 17 00:00:00 2001 From: litianxiang Date: Mon, 12 Jan 2026 11:51:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=9F=A5=E7=9C=8Bredis?= =?UTF-8?q?=E5=86=85=E5=AE=B9=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/api_recommendation.py | 52 ++++++++++++++++++++++++++++++++ app/service/utils/redis_utils.py | 15 +++++++++ 2 files changed, 67 insertions(+) diff --git a/app/api/api_recommendation.py b/app/api/api_recommendation.py index 24b388e..6dcdcc9 100644 --- a/app/api/api_recommendation.py +++ b/app/api/api_recommendation.py @@ -172,4 +172,56 @@ async def recommend( return [path] except Exception as e: logger.error("新版推荐接口失败 [user=%s, category=%s]: %s", user_id, category, e, exc_info=True) + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/redis/user_pref") +async def get_all_user_preferences(): + """ + 获取所有以 user_pref 为前缀的 Redis key 信息,按 account_id 分组 + """ + try: + from app.service.utils.redis_utils import Redis + from app.service.recommendation_system.config import REDIS_KEY_USER_PREF_PREFIX + import json + + # 扫描所有匹配 user_pref:* 的 key + pattern = f"{REDIS_KEY_USER_PREF_PREFIX}:*" + keys = Redis.scan_keys(pattern) + + # 按 account_id 分组 + result = {} + for key in keys: + # 解析 key 格式: user_pref:{account_id}:{category} + parts = key.split(':') + if len(parts) >= 3: + account_id = parts[1] + category = parts[2] + + # 读取对应的值 + value = Redis.read(key) + if value: + try: + vector = json.loads(value) + if account_id not in result: + result[account_id] = {} + result[account_id][category] = { + 'key': key, + 'preference_vector': vector, + 'vector_length': len(vector) + } + except json.JSONDecodeError: + # 如果 JSON 解析失败,保存原始值 + if account_id not in result: + result[account_id] = {} + result[account_id][category] = { + 'key': key, + 'raw_value': value, + 'error': 'JSON decode failed' + } + + return result + + except Exception as e: + logger.error("获取用户偏好数据失败: %s", e, exc_info=True) raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file diff --git a/app/service/utils/redis_utils.py b/app/service/utils/redis_utils.py index a2d446d..8761fde 100644 --- a/app/service/utils/redis_utils.py +++ b/app/service/utils/redis_utils.py @@ -91,6 +91,21 @@ class Redis(object): r = cls._get_r() r.expire(name, expire_in_seconds) + @classmethod + def scan_keys(cls, pattern="*"): + """ + 扫描匹配模式的key + """ + r = cls._get_r() + keys = [] + cursor = 0 + while True: + cursor, partial_keys = r.scan(cursor, match=pattern, count=1000) + keys.extend(partial_keys) + if cursor == 0: + break + return [key.decode('utf-8') if isinstance(key, bytes) else key for key in keys] + if __name__ == '__main__': redis_client = Redis()