0%

go语言操作etcd

go语言操作etcd

etcd的安装、集群部署请参考:v3.5 docs | etcd

1 安装 client

1
go get go.etcd.io/etcd/client/v3

2 连接集群

1
2
3
4
5
6
7
8
9
10
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"}, // 集群各节点ip地址:端口号
DialTimeout: 5 * time.Second, // 连接超时时间
})
if err != nil {
logrus.Errorf("connect to etcd cluster error: %w", err)
return
}
logrus.Info("connect to etcd success")
defer cli.Close()

3 put 和 get 操作

3.1 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// put
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
_, err = cli.Put(ctx, "greeting", "Hello, world!")
cancel()
if err != nil {
logrus.Errorf("put to etcd error: %w", err)
return
}
// get
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
resp, err := cli.Get(ctx, "greeting")
cancel()
if err != nil {
logrus.Errorf("get from etcd error: %w", err)
return
}
for _, pair := range resp.Kvs {
fmt.Printf("%s:%s\n", pair.Key, pair.Value)
}
  • etcd v3 使用gRPC实现远程过程调用,为了确保不产生goroutine泄露(不被使用的goroutine一直占用资源),调用etcd v3 client API时,要传入context.WithTimeout参数,用于通知子goroutine结束,释放资源。

3.2 效果演示

1
2
3
$ go run etcd.go 
INFO[0000] connect to etcd success
greeting:Hello, world!

4 watch 操作

4.1 代码

1
2
3
4
5
6
7
// watch
watchChan := cli.Watch(context.Background(), "greeting")
for wresp := range watchChan {
for _, event := range wresp.Events {
logrus.Infof("Type: %s Key:%s Value:%s\n", event.Type, event.Kv.Key, event.Kv.Value)
}
}
  • 调用Client对象的watch方法,返回1个channel,etcd client对给定的key进行监听,将修改事件记录在channel中
  • 修改事件对象包含:修改类型(更新、删除)、Key、Value 信息

4.2 效果演示

编译、运行程序,

1
2
$ go run etcd.go 
INFO[0000] connect to etcd success

更新操作,

1
$ etcdctl --endpoints=http://localhost:2379 put greeting "Hello, etcd!"                          OK                        

查看程序输出,

1
2
3
$ go run etcd.go 
INFO[0000] connect to etcd success
INFO[0477] Type: PUT Key:greeting Value:Hello, etcd!

删除操作,

1
$ etcdctl --endpoints=http://localhost:2379 del greeting                                         1                       

查看程序输出,

1
2
3
4
$ go run etcd.go 
INFO[0000] connect to etcd success
INFO[0477] Type: PUT Key:greeting Value:Hello, etcd!
INFO[0631] Type: DELETE Key:greeting Value: