美文网首页Golang
groupcache源码(2) Group

groupcache源码(2) Group

作者: Linrundong | 来源:发表于2019-03-02 18:07 被阅读0次

    Group对象

    • Group对象结构以及方法
    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()

    • 根据程序执行顺序,NewHTTPPool()->NewGroup()
    func NewGroup(name string, cacheBytes int64, getter Getter) *Group {
        return newGroup(name, cacheBytes, getter, nil)
    }
    
    // 调用过程
    func main() {
        // groupcache.GetterFunc是一个实现了Getter.Get接口的函数类型,用于转换自定义函数的类型
        // 这样才能符合NewGroup()的Getter类型传入参数要求
        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
            }))
    }
    
    • 需要缓存数据方式需要用户自定义
    • 因此groupcache.GetterFunc用于给自定义函数转换类型

    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唯一标识
        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对象以及添加GroupMap

    相关文章

      网友评论

        本文标题:groupcache源码(2) Group

        本文链接:https://www.haomeiwen.com/subject/mmryuqtx.html