测试代码
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}
<nil>
{"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}
<nil>
{"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}
<nil>
结论是
etcd 的 directory 类型节点可以通过设置recursive=True,watch其直接儿子的新增和删除
孙子节点的新增和删除无法被感知
没有加recursive=True无法感知其儿子的新增和删除
新增和删除的节点会在watch消息里给出,无需再去用get拉取内容。也就是watch给的是类似binlog的增量同步消息
依赖watch来增量同步,需要保证watch不丢掉中间改动。这个可以通过WatcherOptions上的AfterIndex属性来实现,Index就是etcd node的版本。etcd v2 只有节点级别的版本,v3 才有全仓库的版本。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。