redis_client.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import redis
  2. import json
  3. import requests
  4. from typing import Optional
  5. REDIS_HOST = "r-2zeitjlg0gdypzb4v6.redis.rds.aliyuncs.com"
  6. REDIS_PORT = 6379
  7. REDIS_TTL = 1800 # 30分钟
  8. THIRD_PARTY_API = "http://eco.zhongsou.com/eco/user/user.redis.info.groovy"
  9. try:
  10. redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
  11. except Exception:
  12. redis_client = None
  13. def get_app_user(token: str) -> Optional[dict]:
  14. """
  15. 通过第三方 token 获取用户信息
  16. 先查 Redis 缓存,未命中则调第三方接口并写入缓存
  17. Args:
  18. token: App 端传入的第三方 token
  19. Returns:
  20. 用户信息字典,token 无效或接口异常时返回 None
  21. """
  22. cache_key = f"app_user:{token}"
  23. # 1. 查 Redis 缓存
  24. try:
  25. if redis_client:
  26. cached = redis_client.get(cache_key)
  27. if cached:
  28. return json.loads(cached)
  29. except Exception as e:
  30. print(f"Redis 读取失败,降级调第三方接口: {e}")
  31. # 2. 调第三方接口
  32. try:
  33. resp = requests.get(THIRD_PARTY_API, params={"token": token}, timeout=5)
  34. data = resp.json()
  35. if data.get("head", {}).get("status") != 200:
  36. return None
  37. body = data.get("body")
  38. if not body or not body.get("userId"):
  39. return None
  40. user_info = {
  41. "userId": body["userId"],
  42. "userName": body["userName"],
  43. "nickName": body["nickName"],
  44. "mobile": body["mobile"],
  45. "imageUrl": body.get("imageUrl", ""),
  46. "appName": body["appName"],
  47. }
  48. # 3. 写入 Redis 缓存
  49. try:
  50. if redis_client:
  51. redis_client.setex(cache_key, REDIS_TTL, json.dumps(user_info))
  52. except Exception as e:
  53. print(f"Redis 写入失败: {e}")
  54. return user_info
  55. except Exception as e:
  56. print(f"第三方接口调用失败: {e}")
  57. return None