建立Zookeerper连接
private CuratorFramework client;
@Before
public void testConnect(){
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory
.builder()
.connectString("192.168.20.129:2181")
.sessionTimeoutMs(60 * 1000)
.connectionTimeoutMs(15 * 1000)
.retryPolicy(retryPolicy)
.namespace("hello")
.build();
}
create节点 – 持久 临时 顺序
* 1.基本连接
* 2.创建结点 带有数据
* 3.设置结点的类型
* 4.创建多级结点
@Test
public void testCreate() throws Exception {
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{
String path = client.create().withMode(CreateMode.EPHEMERAL).forPath("/app3");
while(true){
}
}
@Test
public void testCreate4() throws Exception{
String path = client.create().creatingParentContainersIfNeeded().forPath("app4/p1");
}
查询结点
- 1.查询数据:get
- 2.查询子节点:ls
- 3.查询结点状态信息ls -s
@Test
public void testGet() throws Exception{
byte[] bytes = client.getData().forPath("/app1");
System.out.println(new String(bytes));
}
@Test
public void testGet2() throws Exception{
List<String> list = client.getChildren().forPath("/app4");
System.out.println(list);
}
@Test
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{
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{
client.delete().forPath("/app1");
client.delete().deletingChildrenIfNeeded().forPath("/app4");
client.delete().guaranteed().forPath("/app1");
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();
}
}