快速上手
创建启用加载器的缓存,观察命中与批量加载。
运行缓存示例
使用 Go 1.27 或更高版本,安装 memo 后将完整示例保存到 main.go 并运行 go run .。在 memo 源码目录可直接执行 go run ./examples/loader。
go get github.com/luminyra/memo// Command loader backs a memo cache with a batch loader: concurrent misses for
// the same key share one load, GetMany loads all its misses in one call, and
// missing keys are cached too.
package main
import (
"context"
"fmt"
"maps"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/luminyra/memo"
)
func main() {
ctx := context.Background()
// 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)
}
// 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())
// 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())
// 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())
}观察何时回源
New 接收带容量和加载器的 Config。Cache.Get 返回值、是否存在和错误。在下方测试中,两次读取命中同一个用户,加载器只运行一次。
loadUsers := func(_ context.Context, ids []int) (map[int]string, error) {
fmt.Println("loading", ids)
users := make(map[int]string)
for _, id := range ids {
users[id] = fmt.Sprintf("user-%d", id)
}
return users, nil
}
cache, err := memo.New(memo.Config[int, string]{Capacity: 100, TTL: time.Minute, Loader: loadUsers})
if err != nil {
panic(err)
}
name, found, _ := cache.Get(context.Background(), 1)
fmt.Println(name, found)
name, found, _ = cache.Get(context.Background(), 1) // served from the cache
fmt.Println(name, found)loading [1]
user-1 true
user-1 true接着使用 GetMany 批量读取 检查一次调用如何处理多个未命中。