zookeeper表现为一个分层的文件系统目录树结构
不同于文件系统之处在于:zk节点可以有字节的数据,而unix文件系统中的目录节点只有子节点
一个节点对应一个应用,节点存储的数据就是应用需要的配置信息
Zookeeper相关的命令 https://www.jianshu.com/p/590852d70e4c
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.5</version>
</dependency>
public class ZkDemo {
private final static Logger logger = Logger.getLogger(ZkDemo.class);
private final static String CONNECT_STRING = "192.168.0.139:2181";
private final static int SESSION_TIMEOUT = 50*1000;
//获得zookeeper实例
public ZooKeeper startZk() throws IOException {
return new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, event -> {
});
}
//关闭zookeeper
public void stopZk(ZooKeeper zooKeeper) throws InterruptedException {
if(zooKeeper != null) {
zooKeeper.close();
}
}
//创建节点
public void createZnode(ZooKeeper zooKeeper, String nodePath, String nodeValue) throws KeeperException, InterruptedException {
zooKeeper.create(nodePath, nodeValue.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public String getZnode(ZooKeeper zooKeeper, String nodePath) throws KeeperException, InterruptedException {
String result = null;
byte[] data = zooKeeper.getData(nodePath, false, new Stat());
result = new String(data);
return result;
}
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZkDemo ZkDemo = new ZkDemo();
String path = "/wangteng";
ZooKeeper zooKeeper = ZkDemo.startZk();
if(zooKeeper.exists(path, false) == null) {
ZkDemo.createZnode(zooKeeper, path, "helloworld");
String nodeValue = ZkDemo.getZnode(zooKeeper, path);
logger.info("create znode and get value: " + nodeValue);
} else {
logger.info("this node is already exist");
}
ZkDemo.stopZk(zooKeeper);
}
}
2019-09-17 02:16:37,064 INFO (com.wang.zookeeper.ZkDemo:main) - create znode and get value: helloworld