java建立maven项目引入zookeeper并实现增删改查

一、新建Maven项目

1、首先在idea中选择maven项目
java建立maven项目引入zookeeper并实现增删改查_第1张图片
2、项目名称
java建立maven项目引入zookeeper并实现增删改查_第2张图片
3、修改Maven配置
首先进入File–>Settings下
java建立maven项目引入zookeeper并实现增删改查_第3张图片
将Maven修改成自己的Maven配置
4、导入ZooKeeper
java建立maven项目引入zookeeper并实现增删改查_第4张图片

二、链接ZooKeeper

1、首先在src–>main–>java下新建类MyZooKeeper.java
java建立maven项目引入zookeeper并实现增删改查_第5张图片
2、设置连接地址、超时时间
java建立maven项目引入zookeeper并实现增删改查_第6张图片

3、建立连接方法并调用
java建立maven项目引入zookeeper并实现增删改查_第7张图片

三、增删改查

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、查看结果
java建立maven项目引入zookeeper并实现增删改查_第8张图片

你可能感兴趣的:(项目整理,java,maven,zookeeper)