import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.List;
/*
*/
public class MyzkTest {
//zk的链接地址
public static final String zkconnect = "服务器ip:2181";
//超时时间
public static final int timeout = 15000;
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = connect();
//create(zooKeeper,"/myzktest","yuanzhihui");
//delete(zooKeeper,"/myzktest");
//setdata(zooKeeper,"/myzktest","xiaoyuan");
query(zooKeeper,"/myzktest");
}
//连接方法
public static ZooKeeper connect() throws IOException {
ZooKeeper zk = new ZooKeeper(zkconnect,timeout,null);
System.out.println("zk连接成功");
return zk;
}
//操作:添加
public static void create(ZooKeeper zooKeeper,String node,String data) throws InterruptedException, KeeperException {
System.out.println("开始创建节点:"+"节点数据为:"+data);
List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
CreateMode createMode = CreateMode.PERSISTENT;
zooKeeper.create(node,data.getBytes(),acl,createMode);
System.out.println("zk节点添加成功");
}
//操作:删除
public static void delete(ZooKeeper zooKeeper,String node) throws Exception{
//先查一下这个节点是否存在
Stat stat =zooKeeper.exists(node,false);
System.out.println("开始删除节点:"+node+"原来的版本号是"+stat.getVersion());
zooKeeper.delete(node,stat.getVersion());
System.out.println("节点删除成功!");
}
//、操作 修改
public static void setdata(ZooKeeper zooKeeper,String node,String data) throws Exception{
//查节点
Stat stat = zooKeeper.exists(node,false);
System.out.println("节点"+node+"原来版本号是"+stat.getVersion());
zooKeeper.setData(node,data.getBytes(),stat.getVersion());
System.out.println("修改成功");
}
//操作 查询
public static void query(ZooKeeper zooKeeper,String node) throws Exception{
String result = new String(zooKeeper.getData(node,false,null));
System.out.println("准备查询数据:"+node+"节点数据为"+result);
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交