CentOS安装zk并连接javaAPI测试

1、安装

可参照Ubuntu 搭建Zookeeper服务进行安装并启动。

2、注意

阿里云环境开放2181端口

2.1 查看已开放端口:

firewall-cmd --permanent --zone=public --list-ports 

2.2 永久的添加该端口。去掉--permanent则表示临时。

firewall-cmd --permanent --zone=public --add-port=2181/tcp

2.3 加载配置,使得修改有效

firewall-cmd --reload

2.4 阿里云安全规则添

 

 3、java来接测试

pom文件依赖引入

        <!-- ZooKeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.4.8</version>
    </dependency>                

测试代码:

public static void main(String[] args) throws Exception {
      /**
       * 超时时间
       */
      final int SESSION_TIME_OUT = 2000;
      CountDownLatch countDownLatch = new CountDownLatch(1);
      ZooKeeper zookeeper = new ZooKeeper("ip:2181", SESSION_TIME_OUT, new Watcher() {
         @Override
         public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
               System.out.println("Watch received event");
               countDownLatch.countDown();
            }
         }
      });
      countDownLatch.await();
      System.out.println("zookeeper connection success");

       List<String> children = zookeeper.getChildren("/", false);
       System.out.println(children);
   }

执行如下则说明访问成功:

4、附注

可通过ZKInspector来查看管理zookeeper节点,下载地址:https://issues.apache.org/jira/secure/attachment/12436620/ZooInspector.zip

解压下载包,进入build目录,点击zookeeper-dev-ZooInspector.jar运行

启动后填写zk服务地址进行连接:

 

 连上之后如下图:

后面就可以对zk的节点进行管理了。

 

posted @ 2019-08-21 23:26  花拾夕  阅读(681)  评论(1编辑  收藏  举报