【ETCD】【实操篇(八)】秒懂 ETCD Watch:三种高效方式监听 Key 变化,不容错过

在这里插入图片描述

在分布式系统中,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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值