【知识库】--Use Zookeeper Cluster Server with Java(150)

来源:互联网 发布:那个房产软件好 编辑:程序博客网 时间:2024/05/16 12:55

单机模拟集群

#定义配置文件如下 :三个端口 clientPort=2182 clientPort=2183 clientPort=2184 三个数据目录 dataDir=/home/zoo/z2/data dataDir=/home/zoo/z3/data dataDir=/home/zoo/z4/data# The number of milliseconds of each ticktickTime=2000# The number of ticks that the initial# synchronization phase can takeinitLimit=10# The number of ticks that can pass between# sending a request and getting an acknowledgementsyncLimit=5# the directory where the snapshot is stored.# do not use /tmp for storage, /tmp here is just# example sakes.dataDir=/home/zoo/z2/data# the port at which the clients will connectclientPort=2182# the maximum number of client connections.# increase this if you need to handle more clients#maxClientCnxns=60## Be sure to read the maintenance section of the# administrator guide before turning on autopurge.## http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance## The number of snapshots to retain in dataDir#autopurge.snapRetainCount=3# Purge task interval in hours# Set to "0" to disable auto purge feature#autopurge.purgeInterval=1server.2=127.0.0.1:3333:3334server.3=127.0.0.1:4444:4445server.4=127.0.0.1:5555:5556

启动命令

zookeeper-3.4.9/bin/zkServer.sh  start  z2/z2.cfg zookeeper-3.4.9/bin/zkServer.sh  start  z3/z3.cfg zookeeper-3.4.9/bin/zkServer.sh  start  z4/z4.cfg 

Java交互

public class Master implements Watcher {    ZooKeeper zk;    String hostPort;    public Master(String hostPort) {        this.hostPort = hostPort;    }    void startZK() throws Exception {        zk = new ZooKeeper(hostPort, 15000, this);    }    void stopZK() throws Exception {        zk.close();    }    public List<String> getChildrenByPath(String path) throws KeeperException, InterruptedException {        return zk.getChildren(path, true);    }    public String addPath(String path, byte[] content) throws KeeperException, InterruptedException {        return zk.create(path, content, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);    }    public String getDataByPath(String path) throws KeeperException, InterruptedException {        return new String(zk.getData(path, true, new Stat()));    }    @Override    public void process(WatchedEvent event) {        System.out.println(event);    }    public static void main(String[] args) throws Exception {        Master m = new Master("10.86.41.28:2182,10.86.41.28:2183,10.86.41.28:2184");        m.startZK();        //创建节点        //        String s = m.addPath("/RR", "zww".getBytes());        //        System.out.println("++++++++++" + s);        Thread.sleep(600);        //获取children节点集合        List<String> root2 = m.getChildrenByPath("/RR");//监听        System.out.println("========2----" + JSON.toJSONString(root2));        //获取节点下的数据        System.out.println("========3----" + m.getDataByPath("/RR"));        Thread.sleep(600000);//wait for a bit        m.stopZK();    }}
0 0
原创粉丝点击