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
| package main
import ( "context" "fmt" "go.etcd.io/etcd/client/v3" "time" )
func main() {
var etcdTestKey = "mohuani-key-1" var etcdTestValue = "mohuani-value-1"
cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"127.0.0.1:2379"}, DialTimeout: time.Second, })
if err != nil { fmt.Println("connect to etcd failed, err: ", err) return } defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second) _, err = cli.Put(ctx, etcdTestKey, etcdTestValue) if err != nil { fmt.Println("put to etcd failed, err: ", err) return } cancel()
ctx, cancel = context.WithTimeout(context.Background(), time.Second) getEtcdResult, err := cli.Get(ctx, etcdTestKey) if err != nil { fmt.Println("get from etcd failed, err: ", err) return } for _, resultValue := range getEtcdResult.Kvs { fmt.Printf("key:%s value:%s\n", resultValue.Key, resultValue.Value) } cancel()
delResult, err := cli.Delete(context.Background(), etcdTestKey) if err != nil { fmt.Println("delete from etcd failed, err: ", err) return } fmt.Println(delResult) fmt.Println("-----")
watchEtcdTestResults := cli.Watch(context.Background(), etcdTestKey) for watchEtcdTestResult := range watchEtcdTestResults { for _, evt := range watchEtcdTestResult.Events { fmt.Printf("type:%s key: %s value: %s\n", evt.Type.String(), evt.Kv.Key, evt.Kv.Value) } }
}
|