实现Java操作ZooKeeper相关 api

转载请说明出处:https://blog.csdn.net/LiaoHongHB/article/details/84336577

连接zookeeper--->connect

package com.ucar.zookeeper.connect;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author liaohong
 * @since 2018/11/19 16:08
 */
public class ZkConnection {

    private Logger logger = LoggerFactory.getLogger(ZkConnection.class);
    private CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZkConnection().getZk();
        while (true) {
            Thread.sleep(5000);
        }
    }

    /**
     * 创建zk连接
     *
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public ZooKeeper getZk() throws IOException, InterruptedException {
        //如果是集群,则逗号隔开,比如192.168.0.219:2181,192.168.0.220:2181,192.168.0.221:2181
        String connStr = "10.103.14.242:2181";
        int session_time = 5000;//每5秒发送一次心跳
        ZooKeeper zk = new ZooKeeper(connStr, session_time, new Watcher() {
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    logger.info("zk connection OK....");
                    latch.countDown();//释放阻塞

                } else if (event.getState().equals(Event.KeeperState.Disconnected)) {
                    // 这时收到断开连接的消息,这里其实无能为力,因为这时已经和ZK断开连接了,只能等ZK再次开启了
                    logger.info("zk Disconnected.........");
                } else if (event.getState().equals(Event.KeeperState.Expired)) {
                    // 这时收到这个信息,表示,ZK已经重新连接上了,但是会话丢失了,这时需要重新建立会话。
                    logger.info("zk Expired");
                    //这里可以进行zk重新连接操作
                    //do Some thing....
                } else if (event.getState().equals(Event.KeeperState.AuthFailed)) {
                    logger.info("zk AuthFailed");
                } else {
                    logger.info("unkonke...." + event.getType());
                }
            }

        });
        logger.info("zk status=" + zk.getState());
        latch.await(5000, TimeUnit.MILLISECONDS);//阻塞,等待zk连接成功,或者5s超时,否则不能往下执行
        logger.info("zk connection OK,lock release....");
        return zk;
    }

}

创建zookeeper节点

package com.ucar.zookeeper.creat;

import com.ucar.zookeeper.connect.ZkConnection;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author liaohong
 * @since 2018/11/19 16:20
 */
public class ZkCreat {

    private Logger logger = LoggerFactory.getLogger(ZkCreat.class);

    private ZkConnection zkConnection = new ZkConnection();

    public void createNode() throws IOException, InterruptedException {
        ZooKeeper zk = zkConnection.getZk();
        try {
            //创建test节点,值为test,不需权限控制,值持久化
            zk.create("/test", "test".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            logger.info("/test 创建成功....");
        } catch (Exception e) {
            logger.info("/test 创建失败....");
            e.printStackTrace();
        }

        //尝试创建已存在的节点
        try {
            //创建test节点,值为test,不需权限控制,值持久化
            zk.create("/test", "test".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            logger.info("/test 第二次创建成功....");
        } catch (Exception e) {
            logger.info("/test 第二次创建失败....");
            e.printStackTrace();
        }

        //创建创建父节点不存在,就直接建子节点
        try {
            //创建/app/app01节点,值为test,不需权限控制,值持久化
            zk.create("/app/app01", "app01".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            logger.info("/app/app01 创建成功....");
        } catch (Exception e) {
            logger.info("/app/app01 创建失败....");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            new ZkCreat().createNode();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

判断节点是否存在

package com.ucar.zookeeper.exist;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author liaohong
 * @since 2018/11/19 16:29
 */
public class ZkIsExist {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ZkConnection zkConnection = new ZkConnection();

    public void isExist() throws IOException, InterruptedException {
        String path = "/test";
        ZooKeeper zk = zkConnection.getZk();
        try {
            Stat stat = zk.exists(path, false);
            if (stat == null) {
                logger.info("节点 path=" + path + "不存在");
            } else {
                logger.info("节点 path=" + path + "存在,stat=" + stat);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            new ZkIsExist().isExist();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ;
    }
}

获取孩子节点

package com.ucar.zookeeper.children;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author liaohong
 * @since 2018/11/19 16:44
 */
public class ZkChildren {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ZkConnection zkConnection = new ZkConnection();

    public void getChildrenNode() {
        try {
            ZooKeeper zk = zkConnection.getZk();
            //创建一些临时节点
            //注意不能再临时节点下创建子节点
            zk.create("/pp", "app".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            //子节点可以是临时的
            zk.create("/pp/app01", "app01".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            zk.create("/pp/app02", "app02".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

            List<String> list = zk.getChildren("/pp", false);
            logger.info("/pp的子节点有:");
            for (String c : list) {
                System.out.print(c + "  ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ZkChildren().getChildrenNode();
    }

}

删除节点

package com.ucar.zookeeper.delete;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author liaohong
 * @since 2018/11/19 16:34
 */
public class ZkDelete {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private ZkConnection zkConnection = new ZkConnection();

    public void delete() throws IOException, InterruptedException {
        ZooKeeper zk = zkConnection.getZk();
        //删除已存在的节点
        try {
            Stat stat = zk.exists("/test", false);
            if (stat != null) {
                zk.delete("/test", stat.getVersion());
                logger.info("删除/test节点成功....");
            } else {
                logger.info("/test节点不存在....");
            }
        } catch (Exception e) {
            logger.info("删除/test失败....");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            new ZkDelete().delete();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

更新节点数据

package com.ucar.zookeeper.update;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author liaohong
 * @since 2018/11/19 16:39
 */
public class ZkUpdate {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ZkConnection zkConnection;

    public void update() throws IOException, InterruptedException {
        ZooKeeper zk = zkConnection.getZk();
        try {
            //创建临时节点/test-update,值为update
            zk.create("/test-update", "update".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            //把值修改为update-2
            zk.setData("/test-update", "update-2".getBytes("utf-8"), 0);
            String data = new String(zk.getData("/test-update", false, null), "utf-8");
            logger.info("/test-update的值为" + data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

授权操作

package com.ucar.zookeeper.auth;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liaohong
 * @since 2018/11/19 16:42
 */
public class ZkAuth {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ZkConnection zkConnection;

    public void auth() {
        try {
            //创建zk1
            ZooKeeper zk1 = zkConnection.getZk();
            //zk1进行认证
            zk1.addAuthInfo("digest", "jianfei".getBytes("utf-8"));
            //zk1创建节点/fei,CREATOR_ALL_ACL进行权限控制
            zk1.create("/fei", "fei".getBytes("utf-8"), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);

            //创建zk2
            ZooKeeper zk2 = zkConnection.getZk();
            //zk2读取节点
            logger.info(new String(zk2.getData("/fei", false, null), "utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

监听操作

package com.ucar.zookeeper.watch;

import com.ucar.zookeeper.connect.ZkConnection;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liaohong
 * @since 2018/11/19 16:47
 */
public class ZkWatch {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ZkConnection zkConnection = new ZkConnection();

    public void watch() {
        try {
            ZooKeeper zk = zkConnection.getZk();
            //监听/watch节点是否存在,
            Stat stat = zk.exists("/watch", new Watcher() {
                public void process(WatchedEvent event) {
                    if (event.getType() == Event.EventType.NodeCreated) {
                        logger.info("exists中监听到..." + event.getPath() + "...创建了");
                    } else if (event.getType() == Event.EventType.NodeDeleted) {
                        logger.info("exists中监听到..." + event.getPath() + "...删除了");
                    } else if (event.getType() == Event.EventType.NodeDataChanged) {
                        logger.info("exists中监听到..." + event.getPath() + "...修改了");
                    }
                }
            });
            if (stat == null) {
                logger.info("/watch 不存在");
                //创建
                String s = zk.create("/watch", "watch".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                logger.info("创建/watch成功..." + s);
                //获取,并监听
                zk.getData("/watch", new Watcher() {
                    public void process(WatchedEvent event) {
                        if (event.getType() == Event.EventType.NodeCreated) {
                            logger.info("getData中监听到..." + event.getPath() + "...创建了");
                        } else if (event.getType() == Event.EventType.NodeDeleted) {
                            logger.info("getData中监听到..." + event.getPath() + "...删除了");
                        } else if (event.getType() == Event.EventType.NodeDataChanged) {
                            logger.info("getData中监听到..." + event.getPath() + "...修改了");
                        }
                    }
                }, null);
                //修改2次
                zk.setData("/watch", "watch2".getBytes("utf-8"), 0);
                zk.setData("/watch", "watch3".getBytes("utf-8"), 1);
                //删除
                zk.delete("/watch", 2);
            } else {
                logger.info("/watch 已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ZkWatch().watch();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值