groupcache 小巧精悍,便于源码学习
几点注意:
1. 我运行了2个groupcache.go, 一个端口 8222 一个端口 8333 都是本地的端口, key会sharding到这2个分布式服务器中
2. client 中请确保 peers.Set("http://localhost:8333", "http://localhost:8222") 中填写的字符串与 服务器中的一致,否则一致性hash算法会错,key映射到服务器ip端口就没那么好, 当然数据还是拿的到的,只是经过了服务器转发
服务器 groupcache.go
package main
import (
"fmt"
"github.com/golang/groupcache"
"net/http"
"os"
)
const (
basePath string = "/basepath/"
groupName = "helloworld"
cacheBytes = 1024 * 1024 * 1024 * 16
)
func main() {
if len(os.Args) < 1 {
fmt.Println("usage: groupcache portNum")
return
}
port := ":" + os.Args[1]
me := "http://localhost" + port
opts := groupcache.HTTPPoolOptions{BasePath: basePath}
peers := groupcache.NewHTTPPoolOpts(me, &opts)
peers.Set("http://localhost:8333", "http://localhost:8222")
groupcache.NewGroup(groupName, cacheBytes, groupcache.GetterFunc(
func(ctx groupcache.Context, key string, dest groupcache.Sink) error {
dest.SetString(key + me)
return nil
}))
http.HandleFunc(basePath, peers.ServeHTTP)
http.ListenAndServe(port, nil)
}
客户端 gcachecli1.go
package main
import (
"fmt"
"github.com/golang/groupcache"
pb "github.com/golang/groupcache/groupcachepb"
)
const (
basePath string = "/basepath/"
)
func getFromPeer(groupName, key string, peers *groupcache.HTTPPool) (value []byte, err error) {
req := &pb.GetRequest{Group: &groupName, Key: &key}
res := &pb.GetResponse{}
peer, ok := peers.PickPeer(key)
if ok == false {
fmt.Println("peers PickPeer failed: ", key)
return
}
err = peer.Get(nil, req, res)
if err != nil {
return nil, err
}
return res.Value, nil
}
func main() {
opts := groupcache.HTTPPoolOptions{BasePath: basePath}
peers := groupcache.NewHTTPPoolOpts("", &opts)
peers.Set("http://localhost:8333", "http://localhost:8222")
val, err := getFromPeer("helloworld", "wjs1", peers)
fmt.Printf("%q %v\n", val, err)
val, err = getFromPeer("helloworld", "wjs4", peers)
fmt.Printf("%q %v\n", val, err)
}
用法
~/gol $ go build groupcache.go
~/gol $ groupcache 8222 &
[groupcache] 71323
~/gol $ groupcache 8333 &
[groupcache<1>] 71329
~/gol $ go run gcachecli1.go
"wjs1http://localhost:8222" <nil>
"wjs4http://localhost:8333" <nil>