zookeeper API

zookeeper API,第1张

zookeeper API API
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

public class ZKAPi {
    public static void main(String[] args) throws Exception {
        String coon="master:2181,node1:2181,node2:2181";//几个节点,写几个
        ZooKeeper zk = new ZooKeeper(coon, 10000, null);//10000为过期时间10s
        

        zk.create("/test","test".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT );
    }
}

监听
import org.apache.zookeeper.*;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static java.lang.Math.E;

public class ZKAPI01 {
    ZooKeeper zk;
 @Before
 public void init() throws Exception {
     zk = new ZooKeeper("master:2181,node1:2181,node2:2181", 3000, null);
 }
 @Test
    public void create() throws KeeperException, InterruptedException {
     zk.create("/test01","test01".getBytes(),
             ZooDefs.Ids.OPEN_ACL_UNSAFE,
             CreateMode.PERSISTENT);
     //Thread.sleep(5000);//临时节点需要指定时间,永久节点不需要
 }
 //参数2个,第一个节点路径 ,第二个监听
    //把监听与节点绑定
 @Test
    public void children()throws Exception{
     zk.getChildren("/test01", new Watcher() {
         //回掉函数
         //触发前提
         //一直监听,当节点删除时显示信息
         public void process(WatchedEvent watchedEvent) {
             System.out.println("当前节点不存在");
         }
     });
     while (true){}
 }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5573825.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存