java crud 操作 package com.uplooking.bigdata.zookeeper;

import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.junit.After; import org.junit.Before; import org.junit.Test;

import java.io.IOException;

/**  * Created by thinkpad on 2016/10/24.  */ public class ZooKeeperTest {

    private ZooKeeper zk;

    @Before
    public void setUp() throws IOException {
        String connectStr = "master:2181";
        int sessionTimeOut = 20000;
        zk = new ZooKeeper(connectStr, sessionTimeOut, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("zookeeper服务监听了" + watchedEvent.getType() + "事件");
            }
        });
    }

    @Test
    public void testCRUD() throws KeeperException, InterruptedException {
        //创建一个zk节点
        String ret = zk.create("/zk", "parent".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("ret: " + ret);
        //获取zk节点中的数据信息
        byte[] bytes = zk.getData("/zk", false, new Stat());
        System.out.println(new String(bytes));
        //创建子节点-->临时子节点
        String child = zk.create("/zk/child", "child".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL);
        System.out.println("child: " + child);
        zk.delete("/zk", -1);
    }

    @After
    public void cleanUp() {

    } }
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐