【Zookeeper】连接ZooKeeper的方式

使用客户端命令连接Zookeeper

连接Server 
使用命令./zkCli.sh -server 127.0.0.1:2181

使用JAVA连接使用ZK

POM添加引用

<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>

使用curator连接使用ZK

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

public class CuratorDemo {

    final static String BasePath = "/curatorTest";

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString("*:2181,*:2182,*:2183").sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("curator").build();

        curatorFramework.start();


        Stat stat = curatorFramework.checkExists().forPath(BasePath + "/node1");
        Object o;
        if (stat == null) {

           o=   curatorFramework.create().creatingParentContainersIfNeeded().
                    withMode(CreateMode.PERSISTENT).forPath(BasePath + "/node1", "0".getBytes());
        }


        //存储Stat
        curatorFramework.getData().storingStatIn(stat).forPath(BasePath + "/node1");

        //更新时使用State
        stat = curatorFramework.setData().withVersion(stat.getVersion()).forPath(BasePath + "/node1", "1".getBytes());
        System.out.println("update => " + stat.getVersion());

        curatorFramework.close();
    }
}

  

posted @ 2019-03-05 11:08  陈泽泽  阅读(2018)  评论(0编辑  收藏  举报