zookeeper java helloworld

zookeeper表现为一个分层的文件系统目录树结构
不同于文件系统之处在于:zk节点可以有字节的数据,而unix文件系统中的目录节点只有子节点
一个节点对应一个应用,节点存储的数据就是应用需要的配置信息

Zookeeper相关的命令 https://www.jianshu.com/p/590852d70e4c

<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.5.5</version>
</dependency>
public class ZkDemo {

    private final static Logger logger = Logger.getLogger(ZkDemo.class);

    private final static String CONNECT_STRING = "192.168.0.139:2181";
    private final static int SESSION_TIMEOUT = 50*1000;

    //获得zookeeper实例
    public ZooKeeper startZk() throws IOException {
        return new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, event -> {

        });
    }

    //关闭zookeeper
    public void stopZk(ZooKeeper zooKeeper) throws InterruptedException {
        if(zooKeeper != null) {
            zooKeeper.close();
        }
    }

    //创建节点
    public void createZnode(ZooKeeper zooKeeper, String nodePath, String nodeValue) throws KeeperException, InterruptedException {
        zooKeeper.create(nodePath, nodeValue.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public String getZnode(ZooKeeper zooKeeper, String nodePath) throws KeeperException, InterruptedException {
        String result = null;
        byte[] data = zooKeeper.getData(nodePath, false, new Stat());
        result = new String(data);
        return result;
    }

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZkDemo ZkDemo = new ZkDemo();
        String path = "/wangteng";
        ZooKeeper zooKeeper = ZkDemo.startZk();
        if(zooKeeper.exists(path, false) == null) {
            ZkDemo.createZnode(zooKeeper, path, "helloworld");
            String nodeValue = ZkDemo.getZnode(zooKeeper, path);
            logger.info("create znode and get value: " + nodeValue);
        } else {
            logger.info("this node is already exist");
        }
        ZkDemo.stopZk(zooKeeper);
    }
}


2019-09-17 02:16:37,064 INFO  (com.wang.zookeeper.ZkDemo:main) - create znode and get value: helloworld
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值