读写流程(伪代码)
读写流程(伪代码)
def get_user(uid):
v = cache.get(key(uid))
if v is not None:
return v
u = db.query(uid)
cache.set(key(uid), u, ttl=300 + rand(60))
return u
def update_user(u):
db.update(u) # 先写数据库
if not cache.delete(key(u.id)):
retry_queue.push(key(u.id)) # 删除失败进补偿队列
写入策略
| 策略 | 行为 | 风险 |
|---|---|---|
| cache-aside | 写库后删缓存,读时回填 | 删除失败出现旧值窗口 |
| write-through | 写缓存同时写库(同步) | 写延迟变高 |
| write-behind | 先写缓存,异步刷库 | 进程崩溃可能丢写 |
删除而不是更新缓存:并发双写下更新操作可能把旧值写回;删除天然幂等,配合 TTL 最终收敛。