golang对etcd存取和数值监测的实现

时间:2022-08-26 21:06:13

测试代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
 
import (
  "fmt"
  "log"
  "time"
 
  "go.etcd.io/etcd/clientv3"
  "golang.org/x/net/context"
)
 
var (
  dialTimeout  = 5 * time.Second
  requestTimeout = 2 * time.Second
  endpoints   = []string{"192.168.99.106:2379", "192.168.99.107:2379", "192.168.99.108:2379"}
)
 
func main() {
  cli, err := clientv3.New(clientv3.Config{
    Endpoints:  endpoints,
    DialTimeout: dialTimeout,
  })
 
  if err != nil {
    log.Fatal(err)
  }
 
  defer cli.Close()
 
  key1, value1 := "testkey1", "value"
 
  ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
  _, err = cli.Put(ctx, key1, value1)
  cancel()
  if err != nil {
    log.Println("Put failed. ", err)
  } else {
    log.Printf("Put {%s:%s} succeed\n", key1, value1)
  }
 
  ctx, cancel = context.WithTimeout(context.Background(), requestTimeout)
  resp, err := cli.Get(ctx, key1)
  cancel()
  if err != nil {
    log.Println("Get failed. ", err)
    return
  }
 
  for _, kv := range resp.Kvs {
    log.Printf("Get {%s:%s} \n", kv.Key, kv.Value)
  }
 
  done := make(chan bool)
 
  go func() {
    wch := cli.Watch(context.Background(), key1)
 
    for item := range wch {
      for _, ev := range item.Events {
        log.Printf("Type:%s, key:%s, value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
      }
    }
  }()
 
  go func() {
    for cnt := 0; cnt < 11; cnt++ {
      value := fmt.Sprintf("%s%d", "value", cnt)
      _, err = cli.Put(context.Background(), key1, value)
      if err != nil {
        log.Println("Put failed. ", err)
      } else {
        log.Printf("Put {%s:%s} succeed\n", key1, value)
      }
    }
  }()
 
  <-done
 
  log.Println("Done!")
}

测试结果如下

golang对etcd存取和数值监测的实现

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000020374026