luminyra
使用指南

批量加载缓存

用 GetMany 一次加载多个缺失键,并减少并发读和缺失数据的重复查询。

配置加载器

Loader 收到一组键并返回找到的值,可将查询合并成一次数据库往返。加载器须支持并发调用。仅设置 Config.Capacity 即可创建缓存,需要回源时再提供加载器。使用 Config.TTL 设置有效期。

memo/examples/loader/main.go
// The Loader receives a batch of keys, like SELECT ... WHERE id IN (...).
var loads atomic.Int32
loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
	loads.Add(1)
	time.Sleep(50 * time.Millisecond) // a slow query
	users := make(map[int]string)
	for _, id := range ids {
		if id <= 100 { // only users 1 to 100 exist
			users[id] = fmt.Sprintf("user-%d", id)
		}
	}
	return users, nil
}

// Only Capacity is required; the zero value of every other field turns
// its feature off.
cache, err := memo.New(memo.Config[int, string]{
	Capacity:     1000,
	TTL:          time.Minute,
	Loader:       loadUsers,
	CacheMissing: true, // remember missing keys instead of querying again
})
if err != nil {
	panic(err)
}
在 GitHub 查看

合并并发读取

十个 goroutine 通过 Cache.Get 同时读取同一个未缓存的键。它们共享一次回源,调用计数为 1。单个调用方取消等待时,其他调用方仍能等待共享的加载。

memo/examples/loader/main.go
// Ten goroutines read the same uncached key; it is loaded once.
var wg sync.WaitGroup
for range 10 {
	wg.Go(func() {
		if _, _, err := cache.Get(ctx, 1); err != nil {
			panic(err)
		}
	})
}
wg.Wait()
fmt.Println("10 concurrent reads, loads:", loads.Load())
在 GitHub 查看

GetMany 批量读取

Cache.GetMany 直接返回命中的值,把其余键放入一次加载调用。发生错误时,它会返回已经找到的值及错误,调用方可分别处理部分结果和失败原因。

memo/examples/loader/main.go
// GetMany returns cached keys directly and loads the rest (2, 3, 999) in
// a single call.
users, err := cache.GetMany(ctx, []int{1, 2, 3, 999})
if err != nil {
	panic(err)
}
for _, id := range slices.Sorted(maps.Keys(users)) {
	fmt.Println(id, users[id])
}
fmt.Println("after GetMany, loads:", loads.Load())
在 GitHub 查看
memo/example_test.go
loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
	fmt.Println("one loader call for", ids)
	return map[int]string{2: "bob", 3: "carol"}, nil
}
cache, _ := memo.New(memo.Config[int, string]{Capacity: 100, Loader: loadUsers})
cache.Set(1, "alice")

users, _ := cache.GetMany(context.Background(), []int{1, 2, 3, 404})
for _, id := range slices.Sorted(maps.Keys(users)) {
	fmt.Println(id, users[id])
}
预期输出
one loader call for [2 3 404]
1 alice
2 bob
3 carol
在 GitHub 查看

缓存缺失数据和短暂使用旧值

Config.CacheMissing 让加载器遗漏的键也能被记住,示例再次读取缺失键时,回源次数不变。配置了 TTL 和加载器时,Config.StaleWhileRevalidate 可在指定窗口返回过期值,同时在后台重新加载。

memo/examples/loader/main.go
// 999 is now cached as missing, so reading it again does not load.
_, found, _ := cache.Get(ctx, 999)
fmt.Println("read 999:", found, "loads:", loads.Load())
在 GitHub 查看

本页目录