Group對(duì)象
- Group對(duì)象結(jié)構(gòu)以及方法
type Group struct {
name string
getter Getter
peersOnce sync.Once
peers PeerPicker
cacheBytes int64 // limit for sum of mainCache and hotCache size
mainCache cache
hotCache cache
loadGroup flightGroup
}
func (g *Group) initPeers()
func (g *Group) Get()
func (g *Group) load()
func (g *Group) getLocally()
func (g *Group) getFromPeer()
func (g *Group) lookupCache()
func (g *Group) populateCache()
NewGroup()
- 根據(jù)程序執(zhí)行順序,NewHTTPPool()->NewGroup()
func NewGroup(name string, cacheBytes int64, getter Getter) *Group {
return newGroup(name, cacheBytes, getter, nil)
}
// 調(diào)用過(guò)程
func main() {
// groupcache.GetterFunc是一個(gè)實(shí)現(xiàn)了Getter.Get接口的函數(shù)類(lèi)型则拷,用于轉(zhuǎn)換自定義函數(shù)的類(lèi)型
// 這樣才能符合NewGroup()的Getter類(lèi)型傳入?yún)?shù)要求
image_cache := groupcache.NewGroup("testGroup", 8<<30, groupcache.GetterFunc(
func(ctx groupcache.Context, key string, dest groupcache.Sink) error {
rows, _ := db.Query("SELECT key, value FROM tbl_cache_map where key = ?", key)
for rows.Next() {
p := new(TblCache)
err := rows.Scan(&p.Key, &p.Value)
if err != nil {
fmt.Println(err)
}
fmt.Printf("get %s of value from tbl_cache_map\n", key)
return dest.SetString("tbl_cache_map.value : " + p.Value)
}
return nil
}))
}
- 需要緩存數(shù)據(jù)方式需要用戶(hù)自定義
- 因此groupcache.GetterFunc用于給自定義函數(shù)轉(zhuǎn)換類(lèi)型
newGroup()
func newGroup(name string, cacheBytes int64, getter Getter, peers PeerPicker) *Group {
if getter == nil {
panic("nil Getter")
}
mu.Lock()
defer mu.Unlock()
// initPeerServerOnce Group唯一標(biāo)識(shí)
initPeerServerOnce.Do(callInitPeerServer)
if _, dup := groups[name]; dup {
panic("duplicate registration of group " + name)
}
g := &Group{
name: name,
getter: getter,
peers: peers,
cacheBytes: cacheBytes,
loadGroup: &singleflight.Group{},
}
if fn := newGroupHook; fn != nil {
fn(g)
}
// 添加GroupMap
groups[name] = g
return g
}
- 初始化Group對(duì)象以及添加GroupMap