使用指南
淘汰与过期
用相同访问序列比较 LRU、LFU、FIFO,区分容量淘汰与 TTL。
比较三种淘汰策略
容量为 3 时先写入 A、B、C,再反复读取 B,最后读 A。用 Cache.Set 写入 D 时需要空出一个位置。下表给出每种策略的淘汰结果。
| 策略 | 保留依据 | 本例淘汰 |
|---|---|---|
LRU | 最近使用 | B |
LFU | 使用频率,频率相同再比较最近使用 | C |
FIFO | 插入顺序 | A |
for _, policy := range []memo.Policy{memo.LRU, memo.LFU, memo.FIFO} {
cache, err := memo.New(memo.Config[string, int]{Capacity: 3, Policy: policy})
if err != nil {
panic(err)
}
// Write a, b and c in order, filling the cache.
cache.Set("a", 1)
cache.Set("b", 2)
cache.Set("c", 3)
// b is read three times (most frequent), c once, a once (most recent).
for _, key := range []string{"b", "b", "b", "c", "a"} {
cache.Get(ctx, key)
}
// Writing a fourth key evicts one entry; All iterates over the rest.
cache.Set("d", 4)
kept := slices.Sorted(maps.Keys(maps.Collect(cache.All())))
fmt.Printf("%-4s keeps %v\n", policy, kept)
}高并发时使用分片
每个分片由一把锁保护,默认只有一个分片。多个 goroutine 同时读写缓存时,可以设置 Config.Shards,按键的哈希把条目分到多个独立加锁的分片:
// Each shard has its own lock and holds Capacity/Shards entries (rounded
// up). Keys are assigned to shards by hash.
cache, err := memo.New(memo.Config[int, string]{
Capacity: 100_000,
Shards: runtime.GOMAXPROCS(0),
})
if err != nil {
panic(err)
}不同 goroutine 写入不同的键时,大多落在不同的分片上,彼此很少需要等锁:
// Eight goroutines write different keys; most writes lock different shards.
var wg sync.WaitGroup
for worker := range 8 {
wg.Go(func() {
for i := range 1000 {
cache.Set(worker*1000+i, fmt.Sprintf("user-%d", worker*1000+i))
}
})
}
wg.Wait()
fmt.Println("entries:", cache.Len())每个分片容纳 Capacity/Shards 个条目(向上取整),并各自执行淘汰策略,因此淘汰顺序只在分片内精确。LRU 和 LFU 每次命中都要更新淘汰顺序;对淘汰顺序要求不高时,FIFO 的命中不修改顺序,并发扩展性最好。
检查现有条目和 TTL
Cache.All 遍历新鲜条目的快照。过期条目在访问或淘汰时惰性清理,Cache.Len 可能仍包含尚未清理的条目。容量淘汰决定空间满时移除谁,Config.TTL 决定一个值多久过期,Config.Jitter 可分散过期时间。
for _, policy := range []memo.Policy{memo.LRU, memo.LFU, memo.FIFO} {
cache, _ := memo.New(memo.Config[string, int]{Capacity: 2, Policy: policy})
cache.Set("a", 1)
cache.Set("b", 2)
cache.Get(context.Background(), "a") // a is now recently and frequently used
cache.Set("c", 3) // evicts one entry
kept := slices.Sorted(maps.Keys(maps.Collect(cache.All())))
fmt.Println(policy, kept)
}LRU [a c]
LFU [a c]
FIFO [b c]