course/etcd/watch.go

31 lines
702 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"context"
"fmt"
"go.etcd.io/etcd/client/v3"
"time"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"43.143.245.135:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
//handle error!
fmt.Println("connect etcd server failed,error:", err)
}
defer cli.Close()
//watch
//派一个哨兵监视wangao这个key的变化新增修改删除
watchchannel := cli.Watch(context.Background(), "wangao")
//从通道中尝试取值(监视的信息)
for wresp := range watchchannel {
for _, evt := range wresp.Events {
fmt.Printf("Type:%v key:%v value:%v\n", evt.Type, string(evt.Kv.Key), string(evt.Kv.Value))
}
}
}