zoukankan      html  css  js  c++  java
  • 【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();
        }
    }
    

      

  • 相关阅读:
    ==和equals
    java 多重继承
    java单例模式
    基础小知识
    print流之错误日志
    print流
    实现读文本文件(IOl流)
    缓冲流(数据的复制粘贴)IO流
    力扣20题、1047(括号合法性,删除字符串中的所有相邻重复项)
    力扣232题、225题(栈实现队列,队列实现栈)
  • 原文地址:https://www.cnblogs.com/zeze/p/10475451.html
Copyright © 2011-2022 走看看