java建立maven项目引入zookeeper并实现增删改查
一、新建Maven项目1、首先在idea中选择maven项目2、项目名称3、修改Maven配置首先进入File–>Settings下将Maven修改成自己的Maven配置4、导入ZooKeeper二、链接ZooKeeper1、首先在src–>main–>java下新建类MyZooKeeper.java2、设置连接地址、超时时间3、建立连接方法并调用三、增删改查1、增加//增加pu
·
一、新建Maven项目
1、首先在idea中选择maven项目
2、项目名称
3、修改Maven配置
首先进入File–>Settings下
将Maven修改成自己的Maven配置
4、导入ZooKeeper
二、链接ZooKeeper
1、首先在src–>main–>java下新建类MyZooKeeper.java
2、设置连接地址、超时时间
3、建立连接方法并调用
三、增删改查
1、增加
//增加
public static void creat(ZooKeeper zooKeeper,String node,String data) throws KeeperException, InterruptedException {
System.out.println("开始添加节点:"+node+",节点数据为:"+data);
List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
CreateMode createMode = CreateMode.PERSISTENT;
zooKeeper.create(node,data.getBytes(),acl,createMode);
System.out.println("zk节点添加成功");
}
2、删除
//删除
public static void delete(ZooKeeper zooKeeper,String node) throws KeeperException, InterruptedException {
Stat stat = zooKeeper.exists(node,false);
System.out.println("开始删除节点:"+node+"节点版本号为:"+stat.getVersion());
zooKeeper.delete(node, stat.getVersion());
System.out.println("删除成功");
}
3、更改
//更改
public static void update(ZooKeeper zooKeeper,String node,String data) throws KeeperException, InterruptedException {
Stat stat = zooKeeper.exists(node,false);
System.out.println("开始修改节点:"+node+"节点版本号为:"+stat.getVersion()+"修改数据为:"+data);
zooKeeper.setData(node,data.getBytes(),stat.getVersion());
System.out.println("zk节点修改成功");
}
4、查询
//查看
public static void query(ZooKeeper zooKeeper,String node) throws KeeperException, InterruptedException {
String result = new String(zooKeeper.getData(node,false,null));
System.out.println("准备查询节点数据:"+node+"-----------"+"节点数据为:"+result);
}
5、测试
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = connect();
creat(zooKeeper,"/zktest1","zktest");
delete(zooKeeper,"/zktest1");
creat(zooKeeper,"/zktest1","zktest");
update(zooKeeper,"/zktest1","myzktest");
query(zooKeeper,"/zktest1");
}
6、查看结果
更多推荐
已为社区贡献3条内容
所有评论(0)