---
title: "Watches"
author: "蝶盟紫"
date: "2015-12-11T20:44:32Z"
tags: []
categories: ["企业架构"]
slug: "watches"
draft: false
lastmod: "2015-12-11T20:44:32Z"
id: 2263550
url: "https://joandora.iteye.com/blog/2263550"
---

Zookeeper的读操作：getData()、getChildren()、exists()，都有可选参数watch。

 

**Definition**

watch是一次性事件，当watch监视的数据发生变化时就会被触发。

 

**One-time trigger**

当znode数据发生变化时，客户端会接收到一个watch事件。只有客户端读操作后，数据变化时服务端才会发送watch事件。后续服务端数据发生变化，客户端不会接收到watch事件，除非客户端第二次发起读操作。

 

**Sent to client**

这意味着事件可能不会到成功到达客户端，可能只在路上。watch是异步发送的，客户端在接收到watch事件时才出发watch里的操作。网络延时或其他因素会造成客户端在不同的时间内接收到watch和返回code的更新。

注意的时，客户端会看到的会保持一致性。

 

**The Data for which watch was set**

node改变有多种方式。这使得zookeeper维护两个watch列表。getData()和exists()对应data watch，getChildren()对应child watch。

 

使用何种watch是根据返回的data类型来决定的。getData()和exists()返回node的data，getChildren()返回子节点列表。

 

setData()会触发data watch。

 

**Things to Remember about Watches**

One time triggers，当你在收到一个watch event后，想再收到znode data的改变通知，就需要再次设置watch。

 

由于one time triggers和在接收watch和发送下一个watch之间的延时，会造成你无法可靠的知道Zookeeper znode每一次的data改变。