4.etcd监听Watch · golang · 看云
~~~
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: 5 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
cli.Put(context.Background(), "/logagent/conf/", "8888888")
for {
// watch key 监听节点
rch := cli.Watch(context.Background(), "/logagent/conf/")
for wresp := range rch {
for _, ev := range wresp.Events {
fmt.Printf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}
}
}
~~~
开启窗口1:
~~~
go run main.go
~~~
返回结果:
~~~
connect succ
~~~
开启窗口2:
~~~
go run main.go
~~~
返回结果:
~~~
connect succ
同时窗口1 返回:
PUT "/logagent/conf/" : "8888888"
~~~