学习 etcd watch api
测试代码
func Test_watch(t *testing.T) { ec, _ := NewEtcdClient([]string{"http://127.0.0.1:2379"}) cli := ec.getEtcdAPI() go func() { watcher := cli.Watcher("/a", &client.WatcherOptions{ Recursive: true, }) for { resp, err := watcher.Next(context.Background()) fmt.Println(resp) fmt.Println(err) } }() cli.Set(context.Background(), "/a/b", "a-b", &client.SetOptions{}) time.Sleep(1 * time.Second) cli.Set(context.Background(), "/a/b/c", "a-b-c", &client.SetOptions{}) time.Sleep(1 * time.Second) cli.Set(context.Background(), "/a/d", "a-d", &client.SetOptions{}) time.Sleep(1 * time.Second) cli.Delete(context.Background(), "/a/b/c", &client.DeleteOptions{}) time.Sleep(1 * time.Second) cli.Delete(context.Background(), "/a/b", &client.DeleteOptions{}) time.Sleep(1 * time.Second)}
结果是
{"action":"set","node":{"key":"/a/b","value":"a-b","modifiedIndex":479128,"createdIndex":479128},"prevNode":{"key":"/a/b","value":"a-b","modifiedIndex":479126,"createdIndex":479126}}&{set {Key: /a/b, CreatedIndex: 479128, ModifiedIndex: 479128, TTL: 0} {Key: /a/b, CreatedIndex: 479126, ModifiedIndex: 479126, TTL: 0} 479127}{"action":"set","node":{"key":"/a/d","value":"a-d","modifiedIndex":479129,"createdIndex":479129},"prevNode":{"key":"/a/d","value":"a-d","modifiedIndex":479127,"createdIndex":479127}}&{set {Key: /a/d, CreatedIndex: 479129, ModifiedIndex: 479129, TTL: 0} {Key: /a/d, CreatedIndex: 479127, ModifiedIndex: 479127, TTL: 0} 479128}{"action":"delete","node":{"key":"/a/b","modifiedIndex":479130,"createdIndex":479128},"prevNode":{"key":"/a/b","value":"a-b","modifiedIndex":479128,"createdIndex":479128}}&{delete {Key: /a/b, CreatedIndex: 479128, ModifiedIndex: 479130, TTL: 0} {Key: /a/b, CreatedIndex: 479128, ModifiedIndex: 479128, TTL: 0} 479129}
结论是
etcd 的 directory 类型节点可以通过设置recursive=True,watch其直接儿子的新增和删除
孙子节点的新增和删除无法被感知
没有加recursive=True无法感知其儿子的新增和删除
新增和删除的节点会在watch消息里给出,无需再去用get拉取内容。也就是watch给的是类似binlog的增量同步消息
依赖watch来增量同步,需要保证watch不丢掉中间改动。这个可以通过WatcherOptions上的AfterIndex属性来实现,Index就是etcd node的版本。etcd v2 只有节点级别的版本,v3 才有全仓库的版本。
关键字:etcd
版权声明
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!