redis_client.py 2.0 KB

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