第三章:缓存策略¶
缓存策略选择¶
按数据特性选择¶
| 数据特性 | 推荐策略 |
|---|---|
| 读多写少 | Cache Aside |
| 写多读少 | Write Through |
| 高一致性 | Write Through |
| 高性能 | Write Behind |
预热策略¶
启动预热¶
def warmup_cache():
"""应用启动时预热缓存"""
# 预热热点数据
hot_users = db.query("SELECT * FROM users WHERE is_hot = 1")
for user in hot_users:
cache.set(f"user:{user.id}", user, ttl=3600)
# 预热配置数据
configs = db.query("SELECT * FROM configs")
for config in configs:
cache.set(f"config:{config.key}", config.value)
定时预热¶
from apscheduler import scheduler
@scheduler.scheduled_job('cron', hour=6)
def daily_warmup():
"""每天早上预热"""
warmup_cache()
过期策略¶
固定过期¶
滑动过期¶
class SlidingCache:
def get(self, key, ttl=3600):
value = self.cache.get(key)
if value:
# 每次访问延长过期时间
self.cache.expire(key, ttl)
return value
永不过期¶
淘汰策略¶
LRU(最近最少使用)¶
LFU(最不经常使用)¶
from collections import defaultdict
class LFUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.freq = defaultdict(int)
def get(self, key):
if key in self.cache:
self.freq[key] += 1
return self.cache[key]
return None
def put(self, key, value):
if len(self.cache) >= self.capacity:
# 淘汰频率最低的
min_key = min(self.freq, key=self.freq.get)
del self.cache[min_key]
del self.freq[min_key]
self.cache[key] = value
self.freq[key] = 1
Redis 淘汰策略¶
| 策略 | 说明 |
|---|---|
| volatile-lru | 淘汰有过期时间的键(LRU) |
| allkeys-lru | 淘汰所有键(LRU) |
| volatile-lfu | 淘汰有过期时间的键(LFU) |
| allkeys-lfu | 淘汰所有键(LFU) |
| volatile-random | 随机淘汰有过期时间的键 |
| allkeys-random | 随机淘汰所有键 |
| volatile-ttl | 淘汰即将过期的键 |
| noeviction | 不淘汰,内存满时报错 |
监控指标¶
def cache_stats():
return {
"hit_rate": cache.get_hit_rate(),
"total_requests": cache.get_total_requests(),
"memory_usage": cache.get_memory_usage(),
"key_count": cache.get_key_count()
}
小结¶
本章学习了:
- ✅ 缓存策略选择
- ✅ 预热策略
- ✅ 过期策略
- ✅ 淘汰策略
- ✅ 监控指标
恭喜完成缓存架构教程! 🎉