java操作zookeeper

创建节点API方法的参数说明如下表所示:

 直接上代码,没时间了 要睡觉了

maven依赖:

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.3.6</version>
        </dependency>

 

public class ZKClient implements Watcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZKClient.class);

    private static volatile ZKClient instance;

    private static int sessionTimeout = 3000;
    private static int retryTime = 3;
    private static String host = "localhost:2181";

    private ZooKeeper zooKeeper;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private ZKClient() {
        connectionZookeeper();
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == KeeperState.SyncConnected) {
            LOGGER.info("Watch received event");
            countDownLatch.countDown();
        }
    }

    public static ZKClient getInstance() {
        if (null == instance) {
            synchronized (ZKClient.class) {
                if (null == instance) {
                    instance = new ZKClient();
                }
            }
        }
        return instance;
    }

    private void connectionZookeeper() {
        try {
            zooKeeper = new ZooKeeper(host, sessionTimeout, this);
            LOGGER.info("get connection zk success....");
        } catch (Exception e) {
            LOGGER.error("connection zk fail MSG:%s", e.getMessage());
        }
    }

    public void colseConnection() throws DevException {
        retryCloseZK(retryTime);
    }

    private void retryCloseZK(int retryTime) throws DevException {
        int currentTime = 0;
        while (true) {
            if (null != zooKeeper) {
                try {
                    zooKeeper.close();
                    break;
                } catch (Exception e) {
                    if (currentTime >= retryTime) {
                        throw new DevException(e.getMessage());
                    }
                }
            } else {
                throw new DevException("not init zkClient");
            }
        }
    }

    public boolean createNode(String path, String data) throws DevException {
        try {
            Stat exists = zooKeeper.exists(path, false);
            if(null != exists){
                zooKeeper.setData(path,data.getBytes(),-1);
                return true;
            }
            String result = zooKeeper.create(
                path,
                data.getBytes(),
                Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
            LOGGER.info(result);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DevException(e.getMessage());
        }
    }

    public String getData(String path) throws DevException {

        try {
            byte[] data = zooKeeper.getData(path, true, null);
            String result = new String(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DevException(e.getMessage());
        }
    }

    public boolean deleteData(String path) throws DevException {
        try {
            zooKeeper.delete(path, -1);
            return true;
        } catch (Exception e) {
            throw new DevException(e.getMessage());
        }
    }

    public boolean updateData(String path,String data)throws DevException{
        try {
            Stat stat = zooKeeper.setData(path, data.getBytes(), -1);
            return true;
        } catch (Exception e) {
            throw new DevException(e.getMessage());
        }
    }

    public List<String> getChild(String path) throws DevException {
        try {
            List<String> children = zooKeeper.getChildren(path, this);
            return children;
        } catch (Exception e) {
            throw new DevException(e.getMessage());
        }
    }


}

测试类:

public class ZookeeperClientTest {
    @Test
    public void zkConnectionTest() throws Exception{
        ZKClient instance = ZKClient.getInstance();
        //Thread.sleep(2000L);
        instance.createNode("/test12","this is my test....");
        instance.updateData("/test12"," 好牛逼的样子是不是");
        String data = instance.getData("/test12");

        System.out.println(data);

        List<String> child = instance.getChild("/");
        for (String datas:child) {
            System.out.println(datas);
        }
    }


}

测试结果(天知道你到底测试成功了没有???):

参考:

https://blog.csdn.net/en_joker/article/details/78688140

https://www.cnblogs.com/weihuang6620/p/10821670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值