这里使用官方的etcd/clientv3包来连接etcd并进行相关操作。

安装

  1. go get go.etcd.io/etcd/clientv3

put和get操作

put命令用来设置键值对数据,get命令用来根据key获取值。

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go.etcd.io/etcd/clientv3"
  7. )
  8. func main(){
  9. cli, err := clientv3.New(clientv3.Config{
  10. Endpoints: []string{"122.51.79.172:2379"},
  11. DialTimeout: 5 * time.Second,
  12. })
  13. if err != nil {
  14. // handle error!
  15. fmt.Printf("connect to etcd failed, err:%v\n", err)
  16. return
  17. }
  18. fmt.Println("connect to etcd success")
  19. defer cli.Close()
  20. // put
  21. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  22. _, err = cli.Put(ctx, "coolops", "test")
  23. cancel()
  24. if err != nil {
  25. fmt.Printf("put to etcd failed, err:%v\n", err)
  26. return
  27. }
  28. // get
  29. ctx, cancel = context.WithTimeout(context.Background(), time.Second)
  30. resp, err := cli.Get(ctx, "coolops")
  31. cancel()
  32. if err != nil {
  33. fmt.Printf("get from etcd failed, err:%v\n", err)
  34. return
  35. }
  36. for _, ev := range resp.Kvs {
  37. fmt.Printf("%s:%s\n", ev.Key, ev.Value)
  38. }
  39. }

watch操作

watch用来获取未来更改的通知。

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go.etcd.io/etcd/clientv3"
  7. )
  8. func main(){
  9. cli, err := clientv3.New(clientv3.Config{
  10. Endpoints: []string{"122.51.79.172:2379"},
  11. DialTimeout: 5 * time.Second,
  12. })
  13. if err != nil {
  14. // handle error!
  15. fmt.Printf("connect to etcd failed, err:%v\n", err)
  16. return
  17. }
  18. fmt.Println("connect to etcd success")
  19. defer cli.Close()
  20. // watch 操作,返回的是一个通道
  21. rch := cli.Watch(context.Background(), "coolops") // <-chan WatchResponse
  22. for wresp := range rch {
  23. for _, ev := range wresp.Events {
  24. fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
  25. }
  26. }
  27. }

安装报错:

  1. go: finding github.com/coreos/pkg latest
  2. # github.com/coreos/etcd/clientv3/balancer/resolver/endpoint
  3. E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\resolver\endpoint\endpoint.go:114:78: undefined: resolver.BuildOption
  4. E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\resolver\endpoint\endpoint.go:182:31: undefined: resolver.ResolveNowOption
  5. # github.com/coreos/etcd/clientv3/balancer/picker
  6. E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\picker\err.go:37:44: undefined: balancer.PickOptions
  7. E:\DEV\Go\pkg\mod\github.com\coreos\etcd@v3.3.19+incompatible\clientv3\balancer\picker\roundrobin_balanced.go:55:54: undefined: balancer.PickOptions

解决:
将go.mod里的prpc改为1.26.0版本

  1. google.golang.org/grpc v1.26.0