redis_client.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. }
  47. # 3. 写入 Redis 缓存
  48. try:
  49. if redis_client:
  50. redis_client.setex(cache_key, REDIS_TTL, json.dumps(user_info))
  51. except Exception as e:
  52. print(f"Redis 写入失败: {e}")
  53. return user_info
  54. except Exception as e:
  55. print(f"第三方接口调用失败: {e}")
  56. return None