Zookeeper(四)——java操作zookeeper

临时节点,是zk的本次会话有效。分布式锁就是用临时节点做的。

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

public class ZookeeperBase {

    static final String CONNECT_ADDR = "192.168.25.128:2181,192.168.25.130:2181,192.168.25.131:2181";
    static final int SESSION_TIMEOUT = 5000;
    static final CountDownLatch connectedLatch = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zk = new ZooKeeper(CONNECT_ADDR, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                Event.KeeperState keeperState = event.getState();
                Event.EventType eventType = event.getType();

                if (Event.KeeperState.SyncConnected == keeperState) {
                    if (Event.EventType.None == eventType) {
                        System.out.println("zk建立连接");
                        connectedLatch.countDown();
                    }
                }
            }
        });

        connectedLatch.await();
        System.out.println("主线程,继续执行");

        String ret = zk.create("/testRoot", "testRoot".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(ret);

        zk.close();
    }
}

猜你喜欢

转载自blog.csdn.net/csdn_kenneth/article/details/83216034
今日推荐