Client Shell command operation
Node type:
Create node - permanent node
First start the zookeeper client----zkCli.sh -server host name: port number
Create node-temporary node
Modify node value
Delete node
Listen for changes in nodes
Changes in node content:
Modify the value under /sanguo on another node
You can see the changes monitored on the hadoop201 node:
Monitor changes in child nodes of a node--ls Path -w Same way
Java API operations
1 guide package
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
</dependency>
2 Create log4j.properties in main/src/sources
# 全局日志配置
log4j.rootLogger=INFO, stdout
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3 zookeeper java api test
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import java.io.IOException;
import java.util.List;
public class ZooKeeperDemo {
static ZooKeeper zooKeeper;
static String connectionString="hadoop200:2181,hadoop201:2181,hadoop202:2181";
static int time=4000000;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
//连接zookeeper集群
zooKeeper = new ZooKeeper(connectionString, time, new Watcher() {
public void process(WatchedEvent watchedEvent) {
}
});
//查看/目录下的节点
List<String> children = zooKeeper.getChildren("/", false);
for (String child : children) {
System.out.print(child+"\t");
}
System.out.println();
//创建一个新节点
if(zooKeeper.exists("/china",false)==null)//判断该节点是否事先存在,如果已经存在再创建会报错
{
zooKeeper.create("/china", "beijing".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
//获取节点内容
byte[] data1 = zooKeeper.getData("/china", false, null);
System.out.println("/china: "+new String(data1));
//删除节点
if(zooKeeper.exists("/CC",false)!=null)
zooKeeper.delete("/CC",Version.REVISION);
//查看删除后的节点
List<String> children1 = zooKeeper.getChildren("/", false);
System.out.println("delete /CC node:");
for (String child : children1) {
System.out.print(child+"\t");
}
System.out.println();
//修改节点内容
zooKeeper.setData("/sanguo","shuguo".getBytes(),-1);
}
}