Client程序,用来修改watch的值。
注意etcdctrl.exe修改不起作用,必须用clientv3库修改程序才能感知。
所以要做一个Client程序
main.go
package main
import (
"context"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: time.Duration(5) * time.Second,
})
if err != nil {
fmt.Println("connect failed, err", err)
return
}
fmt.Println("connect success")
defer cli.Close()
for {
ctx, cancel := context.WithCancel(context.Background())
fmt.Println("Please input xi value:")
var xiValue string
fmt.Scanln(&xiValue)
// 如果输入exit,退出程序
if xiValue == "exit" {
break
}
_, err = cli.Put(ctx, "/xi", xiValue)
cancel()
if err != nil {
fmt.Println("put failed, err: ", err)
return
}
ctx, cancel = context.WithCancel(context.Background())
resp, err := cli.Get(ctx, "/xi")
cancel()
if err != nil {
fmt.Println("get failed, err: ", err)
return
}
for _, ev := range resp.Kvs {
fmt.Printf("%s, %s\n", ev.Key, ev.Value)
}
}
}
watch程序 main.go
package main
import (
"context"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: time.Duration(5) * time.Second,
})
if err != nil {
fmt.Println("connect failed, err", err)
return
}
fmt.Println("connect success")
defer cli.Close()
for {
rch := cli.Watch(context.Background(), "/xi")
for wresp := range rch {
err = wresp.Err()
if err != nil {
fmt.Println(err)
}
for _, ev := range wresp.Events {
fmt.Printf("%s %q %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}
}
}
依赖 go.sum文件
module github.com/zhuge20100104/laonanhai/etcddemo
go 1.15
require (
github.com/coreos/etcd v3.2.30+incompatible
github.com/coreos/go-semver v0.3.0 // indirect
github.com/golang/protobuf v1.4.3 // indirect
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102 // indirect
google.golang.org/genproto v0.0.0-20201105153401-9d023cd09d72 // indirect
)
程序输出如下
有疑问加站长微信联系(非本文作者)