第四章:缓存穿透¶
什么是缓存穿透?¶
解决方案¶
1. 缓存空值¶
def get_user(user_id):
# 先查缓存
cache_key = f"user:{user_id}"
value = redis.get(cache_key)
if value is not None:
if value == "NULL":
return None # 缓存的空值
return json.loads(value)
# 查数据库
user = db.query(User).filter(User.id == user_id).first()
if user:
redis.setex(cache_key, 3600, json.dumps(user.to_dict()))
else:
# 缓存空值,短过期时间
redis.setex(cache_key, 60, "NULL")
return user
2. 布隆过滤器¶
from pybloom_live import BloomFilter
# 初始化布隆过滤器
bf = BloomFilter(capacity=1000000, error_rate=0.001)
# 添加存在的 ID
for user_id in existing_ids:
bf.add(user_id)
def get_user(user_id):
# 先检查布隆过滤器
if user_id not in bf:
return None # 一定不存在
# 可能存在,继续查询
return query_user(user_id)
小结¶
缓存穿透解决要点:
- 缓存空值:短过期时间
- 布隆过滤器:快速判断不存在
下一章我们将学习缓存雪崩。