Etcd和Consul都是非常出名的服务化治理工具。本篇先来讲一下Etcd的使用。
学会使用
安装
go get github.com/coreos/etcd/client
引用
"github.com/coreos/etcd/client"
Example
cfg := client.Config{
Endpoints: []string{"http://127.0.0.1:2379"},
Transport: client.DefaultTransport,
// set timeout per request to fail fast when the target endpoint is unavailable
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
if err != nil {
log.Fatal(err)
}
使用说明
创建客户端
c, err := client.New(cfg)
if err != nil {
log.Fatal(err)
}
设置配置
kapi := client.NewKeysAPI(c)
log.Print("Setting '/foo' key with 'bar' value")
resp, err := kapi.Set(context.Background(), "/foo", "bar", nil)
if err != nil {
log.Fatal(err)
} else {
log.Printf("Set is done. Metadata is %q\n", resp)
}
读取配置
kapi := client.NewKeysAPI(c)
resp, err = kapi.Get(context.Background(), "/foo", nil)
if err != nil {
log.Fatal(err)
} else {
log.Printf("Get is done. Metadata is %q\n", resp)
log.Printf("%q key has %q value\n", resp.Node.Key, resp.Node.Value)
}