gocache is a distributed caching library, adapted from groupcache, intended as a replacement for memcached in many cases.
Install and update this package with go get -u github.com/sinomoe/gocache
.
-
define getter function(used when cache missed) implement Getter interface
getFromDB := gocache.GetterFunc(func(key string) ([]byte, error) { data, err := db.Get(key) // get data from database by the key if err == nil { return data, nil } return nil, fmt.Errorf("%s not exist", key) })
-
initialize a group named as "scores" with max 2048 cached items
goc := gocache.NewGroup("scores", 2<<10, getFromDB)
-
create httpPool instance using local addr
peers := gocache.NewHTTPPool("http://localhost:8001")
-
set peers on httpPool instance, there are three peers, every addr is meant to a gocache peer
peers.SetPeers("http://localhost:8002", "http://localhost:8002", "http://localhost:8003")
-
register httpPool(peers) instance on group instance
goc.RegisterPeers(peers)
MIT © sino