Zookeeper实例ZkClient API-获取节点数据内容
2017-06-14 13:13
501 查看
import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.ZkClient; /** * * @ClassName: Get_Data_Sample * @Description: TODO(ZkClient获取节点数据) * @author * @date 2017年6月14日 下午1:03:46 * */ public class Get_Data_Sample { public static void main(String[] args) throws Exception { String path = "/zk-book"; ZkClient zkClient = new ZkClient("localhost:2181", 5000); zkClient.createEphemeral(path, "123"); zkClient.subscribeDataChanges(path, new IZkDataListener() { public void handleDataDeleted(String dataPath) throws Exception { System.out.println("Node " + dataPath + " deleted."); } public void handleDataChange(String dataPath, Object data) throws Exception { System.out.println("Node " + dataPath + " changed, new data: " + data); } }); // System.out.println(zkClient.readData(path)); zkClient.writeData(path,"456"); Thread.sleep(1000); zkClient.delete(path); Thread.sleep( Integer.MAX_VALUE ); } } 输出: Node /zk-book changed, new data: 456 Node /zk-book deleted.
注意:
getData方法有一个 boolean returnNullIfPathNotExists参数,这样如果当指定的节点不存在就不会抛异常而是返回null.通过调用getData()接口,就可以获得指定节点的内容,这里方法的返回值,在ZkClient内部已经被反序列化成了指定对象。
扩展
参考
1.《从Paxos到Zookeeper:分布式一致性原理与实践》
2. http://javadox.com/com.101tec/zkclient/0.4/org/I0Itec/zkclient/ZkClient.html
相关文章推荐
- Zookeeper实例ZkClient API-获取子节点列表
- Zookeeper实例原生API--异步获取节点数据
- Zookeeper实例原生API--同步获取节点数据
- Zookeeper实例ZkClient API-更新节点内容
- Zookeeper实例ZkClient API-检查节点是否存在
- Zookeeper实例原生API--使用错误权限信息的ZooKeeper会话访问含权限信息的数据节点
- Zookeeper实例原生API--异步更新节点数据
- Zookeeper命令行操作(常用命令;客户端连接;查看znode路径;创建节点;获取znode数据,查看节点内容,设置节点内容,删除节点;监听znode事件;telnet连接zookeeper)
- Zookeeper实例ZkClient API-创建节点
- Zookeeper命令行操作(常用命令;客户端连接;查看znode路径;创建节点;获取znode数据,查看节点内容,设置节点内容,删除节点;监听znode事件;telnet连接zookeeper)
- Zookeeper客户端基本操作java实现——创建连接、创建节点、添加修改节点内容、获取子节点、获取节点数据、删除节点
- Zookeeper实例原生API--异步获取子节点列表
- Zookeeper实例ZkClient API-删除节点
- Zookeeper实例原生API--同步更新节点数据
- Zookeeper实例原生API--同步获取子节点列表
- Zookeeper实例Curator API-使用Curator更新数据内容
- Zookeeper实例原生API--无权限信息的Zookeeper会话访问有权限信息的节点
- Zookeeper客户端API之读取子节点内容(九)
- Zookeeper实例原生API--删除节点
- Zookeeper实例Curator API-使用Curator删除节点