1、导包maven上下载:3.4.6
2、连接:端口2181
参数:集群的每个主机名,会话时间(多长时间没有连上就不行),监视器
public class Demo01 {
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 3000, null);
//创建一个节点,数据
zooKeeper.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//获取数据
Stat stat = new Stat();
byte[] data = zooKeeper.getData("/test", true, stat);
System.out.println(Arrays.toString(data));
}
}
节点类型:
持久:断开连接,创建的节点不删除 短暂:断开连接,节点删除
类型 | 描述 |
---|
CreateMode.PERSISTENT | 永久性节点 | CreateMode.PERSISTENT_SEQUENTIAL | 永久性序列节点 | – | – | CreateMode.EPHEMERAL | 临时节点,会话断开或过期时会删除此节点 | CreateMode.PERSISTENT_SEQUENTIAL | 临时序列节点,会话断开或过期时会删除此节点 | – | – |
操作:
public class Demo03 {
ZooKeeper zooKeeper;
@Before
public void getinit()throws Exception{
//连接,监听器
zooKeeper = new ZooKeeper("master:2181,node1:2181,node2:2181", 2000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
List<String> children = null;
try {
//获取路径监听
children = zooKeeper.getChildren("/", true);
} catch (Exception e) {
e.printStackTrace();
}
//输出所有节点
for (String child : children) {
System.out.println(child);
}
}
});
}
//获取子节点
@Test
public void getChinld()throws Exception{
List<String> children = zooKeeper.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
Thread.sleep(Long.MAX_VALUE);
}
//判断节点是否存在
@Test
public void getExists()throws Exception{
Stat exists = zooKeeper.exists("/d", false);
System.out.println(exists==null?0:1);
}
//修改数据 ,-1表示忽略版本
@Test
public void getUpdata()throws Exception{
Stat stat = zooKeeper.setData("/test", "123456789".getBytes(), -1);
System.out.println(stat==null?0:1);
}
}
|