1 pom 除去slf4j重复引用
<!-- zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.11</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
2 测试代码
/**
* 入门例子
* 如果出现连接错误:
* 配置 windows/System32/drivers/etc/hosts
* 127.0.0.1 admin-PC(电脑名称)
* 127.0.0.1 localhost
*
* admin-PC:2181
* 127.0.0.1:2181
* @return
*/
@RequestMapping("/test")
public String test() {
//路径必须 /
String path = "/dmc";
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
LOG.info("收到事件通知:State->" + watchedEvent.getState()
+ ",Type->:" + watchedEvent.getType()
+ ",Path->:" + watchedEvent.getPath());
if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
}
if (Event.EventType.NodeCreated == watchedEvent.getType()) {
}
if (path.equals(watchedEvent.getPath())) {
}
}
};
try {
//创建ZooKeeper实例
ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 5000, watcher);
//节点存先删除
if (zk.exists(path, watcher) != null) {
zk.delete(path, -1);
}
//创建一个节点,模式是PERSISTENT
zk.create(path, "1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//读取数据
System.out.println("创建节点" + path + ",数据为:" + new String(zk.getData(path, watcher, null)));
//修改节点数据
zk.setData(path, "2".getBytes(), -1);
//删除一个节点
System.out.println(zk.exists(path, watcher));
zk.delete(path, -1);
//节点是否存在
System.out.println(zk.exists(path, watcher));
//连接关闭
zk.close();
} catch (Exception ex) {
System.out.println(ex);
}
return "test";
}
3 注意事项
1)路径必须带 /
2)节点不能重复创建
3)父节点有子节点,父节点不能删除,必须删除子节点