//张三、李四、王二麻同年入伍,还是老乡;一天,他们的父亲来到军营门口。。。
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"github.com/golang/groupcache"
)
const (
ReqPort = "9000" // 对外提供cache服务端口
groupPort = "9090" // cache集群内部通信端口
groupName = "personsrole_cache" // The group name must be unique for each getter.
)
//相当于DB
var imitateDB = map[string]string{
"张三": "指导员",
"李四": "班长",
"王二麻": "副班长",
}
//配置数据源:当cache miss之后,用来执行的load data方法
func getterFunc(ctx context.Context, key string, dest groupcache.Sink) (err error) {
log.Println("from DB: looking up", key)
v, ok := imitateDB[key]
if !ok {
return errors.New("there is no body")
}
dest.SetString(v)
return nil
}
// 启动groupcache,对外提供http服务
func setUpGroup(groupName string, listenPort string) {
//初始化Groupcache对象并设置数据源
//每个cache节点,最大1MB的可用内存;
roleGroup := groupcache.NewGroup(groupName, 1<<20, groupcache.GetterFunc(getterFunc))
//外部请求cache接口
http.HandleFunc("/role", func(rw http.ResponseWriter, r *http.Request) {
roleName := r.FormValue("name")
var role []byte
log.Println("from groupcache: looking up", roleName)
err := roleGroup.Get(context.Background(), roleName, groupcache.AllocatingByteSliceSink(&role))
if err != nil {
rw.WriteHeader(http.StatusNotFound)
rw.Write([]byte("大伯,咱军营没这个人!\n"))
return
}
reply := fmt.Sprintf("老人家,你儿子%s,现在是%s了!\n", roleName, string(role))
rw.Write([]byte(reply))
})
// 启动http服务,监听用户的cache请求
// http://ip:listenPort/role?name=xxx
go http.ListenAndServe(listenPort, nil)
}
//cache request like this : http://ip:listenPort/role?name=xxx
func main() {
me := "http://localhost:groupPort"
peers := groupcache.NewHTTPPool(me)
//cache集群:设置集群信息,用以本机缓存没命中的时候,一致性哈希查找key的存储节点, 并通过http请求访问
peers.Set("http://localhost:groupPort", "http://ip2:groupPort")
// 启动groupcache
setUpGroup(groupName, ":"+ReqPort)
//监听集群内部通信端口:用于向其它cache节点,请求本地不存在的cache;
http.ListenAndServe(":"+groupPort, peers)
}
httppool
负责管理集群中的所有节点,通过http协议使节点之间互相通信,获取存储在其他节点上的缓存;
me := "http://localhost:groupPort"
peers := groupcache.NewHTTPPool(me)
//cache集群:设置集群信息,用以本机缓存没命中的时候,一致性哈希查找key的存储节点, 并通过http请求访问
peers.Set("http://localhost:groupPort", "http://ip2:groupPort")
//监听集群内部通信端口:用于向其它cache节点,请求本地不存在的cache;
http.ListenAndServe(":"+groupPort, peers)
group
负责集群的缓存管理;
包括通过httppool选取key所在节点、缓存不存在时如何获取数据、缓存已满时通过LRU策略腾退空间;
//初始化Groupcache对象并设置数据源
//每个cache节点,最大1MB的可用内存;
roleGroup := groupcache.NewGroup(groupName, 1<<20, groupcache.GetterFunc(getterFunc))
get
获取缓存接口
err := roleGroup.Get(context.Background(), roleName, groupcache.AllocatingByteSliceSink(&role))
//配置httppool
peers := groupcache.NewHTTPPool(localhost:groupPort)
peers.Set(cluster_nodes...)
http.ListenAndServe(":"+groupPort, peers)
//初始化group
group := groupcache.NewGroup(groupName, cacheBytes, groupcache.GetterFunc(loadFuncFromDB))
//how to get cache
group .Get(nil, key, groupcache.AllocatingByteSliceSink(&value))
“groupcache使用及源码分析” https://www.cnblogs.com/B0-1/p/5799094.html