这里写自定义目录标题
- 建立Zookeerper连接
- create节点 -- 持久 临时 顺序
- 查询结点
-
- 删除节点
- 关闭
建立Zookeerper连接
private Curatorframework client;
@Before //任何test执行之前先执行这个方法
public void testConnect(){
//1.第一种方式
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//2.第二种
client = CuratorframeworkFactory
.builder()
.connectString("192.168.20.129:2181")
.sessionTimeoutMs(60 * 1000)
.connectionTimeoutMs(15 * 1000)
.retryPolicy(retryPolicy)
.namespace("hello")//.namespace("hello").build() 名称空间 以后操作都在这个根下
.build();
}
create节点 – 持久 临时 顺序
* 1.基本连接
* 2.创建结点 带有数据
* 3.设置结点的类型
* 4.创建多级结点
@Test
public void testCreate() throws Exception {
//1.基本创建
//如果创建结点,没有指定数据,则默认将当前客户端ip作为数据存储
String path = client.create().forPath("/app1");
}
@Test
public void testCreate2() throws Exception{
//带数据
String path = client.create().forPath("/app2","hehe".getBytes());
}
@Test
public void testCreate3() throws Exception{
//3.设置节点的类型
//默认类型:持久化 CreateMode.EPHEMERAL
String path = client.create().withMode(CreateMode.EPHEMERAL).forPath("/app3");
while(true){
}
}
@Test
public void testCreate4() throws Exception{
//创建多级节点 /app1/p1
//creatingParentContainersIfNeeded 父节点不存在则存放父节点
String path = client.create().creatingParentContainersIfNeeded().forPath("app4/p1");
}
查询结点
- 1.查询数据:get
- 2.查询子节点:ls
- 3.查询结点状态信息ls -s
@Test//1
public void testGet() throws Exception{
byte[] bytes = client.getData().forPath("/app1");
System.out.println(new String(bytes));
}
@Test//2
public void testGet2() throws Exception{
List list = client.getChildren().forPath("/app4");
System.out.println(list);
}
@Test//3
public void testGet3() throws Exception{
Stat status=new Stat();
client.getData().storingStatIn(status).forPath("/app1");
System.out.println(status);
}
修改数据
@Test
public void testSet() throws Exception{
client.setData().forPath("/app1","helloo".getBytes());
}
@Test
public void testSetForVersion() throws Exception{
//int version=0;//查询出来的
//用状态信息查出来
Stat status=new Stat();
client.getData().storingStatIn(status).forPath("/app1");
int version=status.getVersion();
client.setData().withVersion(version).forPath("/app1","helloo".getBytes());
}
删除节点
* 1.删除单个节点 delete
* 2.删除带有子节点的节点 deleteall
* 3.必须成功的删除
* 4.回调
@Test
public void testdelete() throws Exception{
//1.
client.delete().forPath("/app1");
//2.
client.delete().deletingChildrenIfNeeded().forPath("/app4");
//3.会话超时 发不到服务端 重试方法
client.delete().guaranteed().forPath("/app1");
//4.
client.delete().guaranteed().inBackground(new BackgroundCallback() {
@Override
public void processResult(Curatorframework curatorframework, CuratorEvent curatorEvent) throws Exception {
System.out.println(curatorEvent);
}
}).forPath("/app1");
}
关闭
@After
public void close(){
if(client!=null){
client.close();
}
}