go groupcache 用法示例

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值