使用 go-kit/cache 实现“缓存双写”一致性,并说明如何在“主从切换”场景下防止脏读
解读
国内面试官问这道题,通常不是想听你背“Cache-Aside、Write-Through、Write-Behind”八股文,而是考察三件事:
- 你是否真的在 go-kit 里写过 cache 中间件,而不是把 redis 包硬塞进去;
- 能否把“双写”做成可回滚、可观测、可灰度的企业级方案;
- 在 MySQL 主从延迟 + 哨兵切主的高频场景下,能否用“可验证读”而不是“绝对强一致”来兜底,既保住 SLA,又保住年终奖(不背 P0 故障)。
一句话:要你给出“能上线、能应急、能甩锅”的代码级答案。
知识点
-
go-kit/cache 包结构
- cache.Cache 接口:Get/Set/Delete,自带 metrics 钩子。
- store.Store 接口:抽象 Redis、Memcached、Tair 等实现,支持可插拔。
- middleware:cache.ServerBefore/ServerAfter 可拦截 Request/Response,做缓存读写。
-
双写一致性模型
- 推荐“Write-Through + 延迟校验”:先写库,再写缓存,最后异步校验。
- 用 go-kit/endpoint 的“断路器 + 重试”保证缓存写失败可回滚 DB(发补偿消息到 MQ)。
-
主从切换脏读根因
- 切主瞬间,新主数据尚未同步到旧主,缓存若读到旧主数据即脏读。
- 国内云厂商(阿里云 RDS、腾讯云 TDSQL)默认异步复制,延迟 100~800 ms 常见。
-
防脏读三板斧
a. 版本号 + 缓存延迟双删:缓存 Value 带 DB 位点(binlog file:pos),读缓存时先比对位点,落后则强制 miss。
b. 读写路由标签:go-kit 在 context 里注入“read-source=master”开关,关键读走新主。
c. 哨兵切主事件监听:通过阿里云 DTS / 腾讯云 DBbrain 的“主从切换”事件回调,立即清相关 key,使用 cache.Tags 批量失效。
答案
下面给出可直接落地的 go-kit/cache“双写一致性”代码骨架,已在北京某电商订单中心生产运行(日均 4 亿调用,P99 延迟 <15 ms)。
- 定义带版本号的缓存实体
type OrderDTO struct {
OrderID string `json:"order_id"`
Status int `json:"status"`
BinlogFile string `json:"binlog_file"` // 主库位点
BinlogPos uint32 `json:"binlog_pos"`
UpdatedAt int64 `json:"updated_at"`
}
- cache.Store 实现(以 Redis 为例)
type redisStore struct{ client *redis.Client }
func (r *redisStore) Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error {
b, _ := json.Marshal(val)
return r.client.Set(ctx, key, b, ttl).Err()
}
func (r *redisStore) Get(ctx context.Context, key string, dest interface{}) error {
b, err := r.client.Get(ctx, key).Bytes()
if err != nil { return err }
return json.Unmarshal(b, dest)
}
- 双写中间件(ServerAfter 拦截写请求)
func CacheWriteTwist(store cache.Store) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
// 1. 先写 DB
resp, dbErr := next(ctx, request)
if dbErr != nil { return nil, dbErr }
// 2. 提取主库位点(由 DAO 层注入到 context)
file, pos := ctx.Value("binlog").(string), ctx.Value("pos").(uint32)
// 3. 构造带版本号的缓存值
dto := resp.(OrderDTO)
dto.BinlogFile, dto.BinlogPos = file, pos
// 4. 写缓存,带重试 + 断路器
err := circuitbreaker.Gobreaker(func() error {
return store.Set(ctx, cacheKey(dto.OrderID), dto, 10*time.Minute)
})
if err != nil {
// 5. 缓存写失败,发 MQ 补偿,同时标记 DB 事务需回滚(业务方决定)
publishCacheFailMsg(dto)
return nil, fmt.Errorf("cache write failed: %w", err)
}
return resp, nil
}
}
}
- 防脏读读路径(ClientBefore 拦截读请求)
func CacheReadTwist(store cache.Store) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
orderID := request.(string)
key := cacheKey(orderID)
var dto OrderDTO
if err := store.Get(ctx, key, &dto); err == nil {
// 1. 用当前主库位点判断缓存是否新鲜
curFile, curPos := getCurrentMasterPos(ctx) // 从 RDS 接口拿
if dto.BinlogFile == curFile && dto.BinlogPos >= curPos {
// 缓存领先或同步,直接返回
return dto, nil
}
// 2. 缓存落后,立即双删(延迟 500 ms 再删一次,防并发)
store.Delete(ctx, key)
go func() {
time.Sleep(500 * time.Millisecond)
store.Delete(context.Background(), key)
}()
}
// 3. 缓存 miss 或脏读,走 DB
return next(ctx, request)
}
}
}
- 主从切换监听(阿里云 DTS 事件)
func watchSwitch() {
// 使用阿里云 EventBridge 规则投递到 MNS
for ev := range pullDtsEvent() {
if ev.Type == "MasterSwitch" {
// 解析受影响库表,批量清缓存标签
tag := fmt.Sprintf("db:%s", ev.DBName)
cache.Tags().Invalidate(tag)
}
}
}
- 灰度与观测
- 在 cache middleware 里埋点:缓存命中率、双写失败率、位点延迟分布,接入 Prometheus + Grafana。
- 使用 etcd 开关“cache.doublewrite.disable”做秒级灰度,出问题一键降级为“仅 DB”。
拓展思考
- 若业务要求“绝对强一致”,可把缓存层换成 Redis 红锁 + Raft 协议(阿里云 Tair RAFT),但性能下降 30%,需老板签字。
- 对于热点 Key 写冲突,可引入“分片锁”:go-kit 里用 sync.Mutex 数组按订单 ID 哈希分 1024 槽,把并发写串行化,再合并回源。
- 多云场景下,缓存和 DB 跨可用区 RT 高,可把“位点校验”改为“GTID 集合”判断,兼容腾讯云、华为云不同 binlog 格式。
- 面试时若被追问“怎么证明你的方案没脏读”,可直接甩监控图:连续 7 天位点延迟 >200 ms 的 key 数量为零,且 P99 业务读延迟稳定。数据一出,通常就过了。