if c.lru == nil { c.lru = lru.New(c.cacheBytes, nil) }
c.lru.Add(key, value) }
get 方法用于查找缓存值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// get 查找 func(c *cache)get(key string)(value ByteView, ok bool) { c.mu.Lock() defer c.mu.Unlock() // 底层lru缓存为空,直接返回 if c.lru == nil { return } // 在底层lru缓存中查找 if v, ok := c.lru.Get(key); ok { return v.(ByteView), ok }
return }
Group 实现
dawncache.go
Group 是 DawnCache 最核心的数据结构,不仅分组将缓存数据进行了简单的划分;而且负责与用户的交互,并且控制缓存值存储和获取的流程。
var db = map[string]string{ "Tom": "630", "Jack": "589", "Sam": "567", }
funcTestGet(t *testing.T) { loadCounts := make(map[string]int, len(db)) gee := NewGroup("scores", 2<<10, GetterFunc( func(key string)([]byte, error) { log.Println("[SlowDB] search key", key) if v, ok := db[key]; ok { if _, ok := loadCounts[key]; !ok { loadCounts[key] = 0 } loadCounts[key]++ return []byte(v), nil } returnnil, fmt.Errorf("%s not exist", key) }))
for k, v := range db { if view, err := gee.Get(k); err != nil || view.String() != v { t.Fatal("failed to get value of Tom") } if _, err := gee.Get(k); err != nil || loadCounts[k] > 1 { t.Fatalf("cache %s miss", k) } }
if view, err := gee.Get("unknown"); err == nil { t.Fatalf("the value of unknow should be empty, but %s got", view) } }
funcTestGetGroup(t *testing.T) { groupName := "scores" NewGroup(groupName, 2<<10, GetterFunc( func(key string)(bytes []byte, err error) { return })) if group := GetGroup(groupName); group == nil || group.name != groupName { t.Fatalf("group %s not exist", groupName) }
if group := GetGroup(groupName + "111"); group != nil { t.Fatalf("expect nil, but %s got", group.name) } }