1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import redis import time from typing import Optional
r = redis.Redis(host='localhost', port=6379, db=0)
def get_from_db(user_id: str) -> dict: """模拟从数据库读取数据""" time.sleep(1) return {"user_id": user_id, "username": f"user_{user_id}", "email": f"user{user_id}@test.com"}
def get_user(user_id: str) -> dict: key = f"user:{user_id}" user = r.get(key) if user: print("✅ 缓存命中") return eval(user) else: print("❌ 缓存未命中,从数据库查询") user = get_from_db(user_id) r.setex(key, 300, str(user)) return user
def update_user(user_id: str, new_data: dict): r.delete(f"user:{user_id}")
|