# -*- coding: utf-8 -*- """Redis 缓存层。 - pl:stats 后台统计(TTL 30s,任何订单写入即失效) - pl:user:{id} 鉴权用户信息(TTL 60s,用户资料变更即失效) Redis 不可用时全部静默降级为直查数据库,不影响可用性。 """ import json import os import redis _client = None STATS_KEY = "pl:stats" USER_KEY = "pl:user:%s" STATS_TTL = 30 USER_TTL = 60 def client(): global _client if _client is None: url = os.environ.get("PL_REDIS_URL", "redis://127.0.0.1:6379/0") _client = redis.Redis.from_url( url, socket_timeout=2, socket_connect_timeout=2, decode_responses=True ) return _client def get_json(key): try: raw = client().get(key) return json.loads(raw) if raw else None except Exception: return None def set_json(key, value, ttl): try: client().setex(key, ttl, json.dumps(value, ensure_ascii=False)) except Exception: pass def delete(*keys): try: client().delete(*keys) except Exception: pass def get_user(user_id: int): return get_json(USER_KEY % user_id) def set_user(user_dict: dict): set_json(USER_KEY % user_dict["id"], user_dict, USER_TTL) def invalidate_user(user_id: int): delete(USER_KEY % user_id) def get_stats(): return get_json(STATS_KEY) def set_stats(stats: dict): set_json(STATS_KEY, stats, STATS_TTL) def invalidate_stats(): delete(STATS_KEY)