這一個 golang 裡面非常帥氣的 library ,作者是原 memcached 的作者之一,主要就是讓 cache 機制再簡化

集群的部署能力也還不錯,完全不用再管 server instance ,我對這種,以簡單為名的 library 最沒有招架能力了

https://github.com/golang/groupcache

使用上也是非常的帥氣,可以參考 OSCON 的簡報

http://talks.golang.org/2013/oscon-dl.slide#1

詳細的使用上可以參考, source code ,或是 test case,還有很多種用法

以下是我用的範例,您可以用在很多地方,像是外部 url fetch ,或是很重的 query 或是檔案 IO 之類的
就是平常,你 cache 怎麼用,就可以怎麼用,cache 只有支援 拿,和寫,

以下的例子用這樣拿資料,我的 cache key 大概到小時,就用自己算每小時不同的 key
FileInfoCache.Get(nil, cacheFileInfo, groupcache.AllocatingByteSliceSink(&data))

另外,FileInfoFetch 就是另外一個做很多 disk IO 的工作
dest.SetBytes(FileInfoFetch(path))



// Example for groupcache
// snip from my code

var (
FileInfoCache *groupcache.Group
)

func init(){

//////////////////////////////////////////
// init book query cache
//cacheAddr := “127.0.0.1:55555”
//peers := groupcache.NewHTTPPool(“http://” + cacheAddr)
// the cache key is compose with timestamp hour
// 2006-01-02 15!!!url
getter := groupcache.GetterFunc(func(ctx groupcache.Context, key string, dest groupcache.Sink) error {
keys := strings.SplitN(key, “!!!”, 2)
//ts := keys[0]
path := keys[1]
dest.SetBytes(FileInfoFetch(path))
return nil
})


if FileInfoCache == nil {
// cache not been init
// allocate 64 MB memory for groupcache
FileInfoCache = groupcache.NewGroup(“FileInfo”, 64«20, getter)
}


}




你看,帥不帥氣,完全不需要另外跑,cache server daemon ,如果要組成 cluster 就直接在程式裡用 HTTPPool 的服務