Zookeeper——java操作客户端(有代码注释可运行)

先引入Zookeeper原生的jar包

  <!--zookeeper连接包-->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.6.0</version>
        </dependency>

其他看代码和注释


public class CrudZookeeper {
    
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    //zookeeper的连接路径
    private final static String ZOOKEEP_UER="49.233.186.66:2181";

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper(ZOOKEEP_UER, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //如果连接上了
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        System.out.println("连接上了");
                        countDownLatch.countDown();
                    }
                    //如果节点发生了变化
                if(watchedEvent.getType()==Event.EventType.NodeDataChanged){
                    System.out.println("节点数据发生变化,节点路径为"+watchedEvent.getPath());
                }
            }
        });
        //防止zookeeper还没连接上,代码就往下走
        countDownLatch.await();
        //stat是节点的一些相关状态信息
        Stat stat = new Stat();
        //创建节点, 路径/值/ACL权限/节点类型
     //   zooKeeper.create("/ccc","value2".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        //获取节点, 路径/是否监听/stat
        byte[] data = zooKeeper.getData("/ccc", true, stat);
        System.out.println(new String(data));
        System.out.println(stat);
        //修改数据   version传入-1时不进行版本维护
        zooKeeper.setData("/ccc","value2".getBytes(),-1);
        //删除数据
        zooKeeper.delete("/ccc",-1);

        //获取子节点  watch代表当节点或数据发生改变时通知客户端
        List<String> children = zooKeeper.getChildren("/testauth", true);

    }
}

值得注意的是,watch机制是有有效性的,一次设置为true,就只能监听一次
如下代码,当第三行没有时,上面代码种的监听修改便只能打印一次!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值