Zookeeper是Apache Hadoop的一个子项目,本质是一个分布式小文件系统,主要解决分布式系统应用中遇到的数据管理问题(一致性问题):统一命名服务,状态同步服务,集群管理,分布式应用配置项的管理。
Zookeeper有四种类型的节点:
节点在创建后其类型不能被修改。
/** * Zookeeper测试类 * Created by huanghuan on 2017/2/8. */ @Log public class ZookeepeTest { private ZooKeeper zooKeeper; public ZooKeeper connect(String host) throws Exception { zooKeeper = new ZooKeeper(host, 2181, watchedEvent -> { log.info("# connect " + watchedEvent.toString()); }); return zooKeeper; } public void close() throws InterruptedException { zooKeeper.close(); } public String createNode(String path, byte[] data, CreateMode createMode) throws Exception { zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode); } public void deleteNode(String path) throws Exception { zooKeeper.delete(path, zooKeeper.exists(path, true).getVersion()); } public Stat watch(String path) throws KeeperException, InterruptedException { Stat stat = new Stat(); zooKeeper.getData(path, watchedEvent -> { log.info("# event " + watchedEvent.toString()); }, stat); return stat; } }
public static void main(String args[]) throws Exception { ZookeeperTest zookeeperTest=new ZookeeperTest(); zookeeperTest.connect("127.0.0.1"); log.info(zookeeperTest.createNode("/test", "test".getBytes(), CreateMode.PERSISTENT)); for (int i = 0; i < 5; i++) { log.info(zookeeperTest.createNode("/test/child", null, CreateMode.PERSISTENT_SEQUENTIAL)); } }
结果为:
信息: /test 信息: /test/child0000000000 信息: /test/child0000000001 信息: /test/child0000000002 信息: /test/child0000000003 信息: /test/child0000000004
临时节点的创建原理类似,但在客户端断开连接后,临时节点的内容将消失。
public static void main(String args[]) throws Exception { ZookeeperTest zookeeperTest = new ZookeeperTest(); zookeeperTest.connect("127.0.0.1"); zookeeperTest.createNode("/test/watch", "watch".getBytes(), CreateMode.PERSISTENT); zookeeperTest.watch("/test/watch"); zookeeperTest.deleteNode("/test/watch"); }
结果为:
信息: # connect WatchedEvent state:SyncConnected type:None path:null 信息: # connect WatchedEvent state:SyncConnected type:NodeDeleted path:/test/watch 信息: # event WatchedEvent state:SyncConnected type:NodeDeleted path:/test/watch