在分布式系统中,etcd 是一个高可用的键值存储,广泛用于存储和共享配置信息、服务发现以及协调任务等。针对 etcd 集群的watch操作,可以通过多种方式实现。本文将演示如何使用三种常见方式进行事务操作:etcdctl 命令行工具、Go 客户端和 Java 客户端。
目录
一、使用EtcdCtl工具来执行事务操作
1.1、设置环境变量(可选)
export ETCDCTL_API=3
export ETCDCTL_ENDPOINTS=http://localhost:2379
1.2、使用etcdctl watch [keu]执行watch操作
现在一个终端上面执行etcdctl watch watch_key
在另外一个终端上端上执行etcdctl put watch_key
D:\data>etcdctl watch watch_key
D:\data>etcdctl put watch_key value1
1.3、通过etcdctl watch -h来查看相关帮助信息
D:\data>etcdctl watch -h
NAME:
watch - Watches events stream on keys or prefixes
USAGE:
etcdctl watch [options] [key or prefix] [range_end] [--] [exec-command arg1 arg2 ...] [flags]
OPTIONS:
-h, --help[=false] help for watch
-i, --interactive[=false] Interactive mode
--prefix[=false] Watch on a prefix if prefix is set
--prev-kv[=false] get the previous key-value pair before the event happens
--progress-notify[=false] get periodic watch progress notification from server
--rev=0 Revision to start watching
---
### 二、使用go 客户端进行事务操作
#### 2.1、安装 Go 客户端库
#### 2.2、示例代码
```go
func init() {
// 初始化etcd客户端
var err error
cli, err = clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"}, // 替换为你的etcd集群地址
DialTimeout: 5 * time.Second,
})
if err != nil {
log.Fatal(err)
}
}
func watch_key() {
watch := cli.Watch(context.Background(), "watch_key")
for {
select {
case watchResponse := <-watch:
for _, event := range watchResponse.Events {
fmt.Printf("Type: %s, Key: %s, Value: %s\n", event.Type, event.Kv.Key, event.Kv.Value)
}
}
}
}
func main() {
defer cli.Close()