客户端操作zookeeper服务代码示例

简介:

 1.通过org.apache.zookeeper.ZooKeeper来操作zookeeper服务

  有关zookeeper服务的部署参见文:http://aiilive.blog.51cto.com/1925756/1684145 下文将有代码示例展示通过编码方式在应用中启动zookeeper服务。

 

  ZooKeeper类对zookeeper服务的简单操作示例代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package  secondriver.dubbo.client;
 
import  org.apache.zookeeper.*;
import  org.apache.zookeeper.data.Stat;
 
import  java.io.IOException;
import  java.util.List;
import  java.util.concurrent.TimeUnit;
 
/**
  * Author : secondriver
  */
public  class  TestZookeeper {
 
     public  static  void  main(String[] args)  throws  IOException, KeeperException, InterruptedException {
 
         //创建zookeeper客户端
         ZooKeeper zooKeeper =  new  ZooKeeper( "192.168.88.153:2181" 1000 new  Watcher() {
             @Override
             public  void  process(WatchedEvent event) {
                 System.out.println( "EventType:"  + event.getType().name());
             }
         });
 
         //获取"/" node下的所有子node
         List<String> znodes = zooKeeper.getChildren( "/" true );
         for  (String path : znodes) {
             System.out.println(path);
         }
 
         //创建开放权限的持久化node "/test"
         String rs = zooKeeper.create( "/test" "test" .getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode
                 .PERSISTENT);
         System.out.println(rs);
 
         //同步获取"/test" node的数据
         Stat stat =  new  Stat();
         byte [] data = zooKeeper.getData( "/test" true , stat);
         System.out.println( "value="  new  String(data));
         System.out.println(stat.toString());
 
 
         //异步获取"/test" node的数据
         zooKeeper.getData( "/test" true new  AsyncCallback.DataCallback() {
             @Override
             public  void  processResult( int  rc, String path, Object ctx,  byte [] data, Stat stat) {
                 System.out.println(rc);
                 System.out.println(path);
                 System.out.println(ctx);
                 System.out.printf( new  String(data));
                 System.out.println(stat.toString());
 
             }
         },  "Object ctx ..(提供的外部对象)" );
 
         TimeUnit.SECONDS.sleep( 10 );
 
         zooKeeper.close();
     }
}


  上述代码依赖zookeeper包

 

1
2
3
4
5
< dependency >
     < groupId >org.apache.zookeeper</ groupId >
     < artifactId >zookeeper</ artifactId >
     < version >3.4.6</ version >
</ dependency >


 2.通过zkclient操作zookeeper服务

  zkclient github: https://github.com/sgroschupf/zkclient 

  后续有二次开发的版本:

  项目: https://github.com/adyliu/zkclient

  文档: https://github.com/adyliu/zkclient/wiki/tutorial

 

  下文代码示例使用sgroschupf/zkclient,依赖Zookeeper包。

  maven  sgroschupf/zkclient

 

1
2
3
4
5
< dependency >
     < groupId >com.101tec</ groupId >
     < artifactId >zkclient</ artifactId >
     < version >0.5</ version >
</ dependency >

 

  应用内server+client:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package  secondriver.dubbo.server;
 
import  org.I0Itec.zkclient.IDefaultNameSpace;
import  org.I0Itec.zkclient.ZkClient;
import  org.I0Itec.zkclient.ZkServer;
import  org.apache.zookeeper.CreateMode;
 
import  java.io.IOException;
/**
  * Author : secondriver
  */
public  class  TestI0ItecZk {
 
     public  static  void  main(String[] args)  throws  IOException {
         //Server + Client
         ZkServer zkServer =  new  ZkServer( "D:/data" "D:/log" new  IDefaultNameSpace() {
             @Override
             public  void  createDefaultNameSpace(ZkClient zkClient) {
                 zkClient.create( "/default" "defalut-name-space" , CreateMode.PERSISTENT);
             }
         });
 
         zkServer.start();
 
         ZkClient zkClient = zkServer.getZkClient();
 
         boolean  exists = zkClient.exists( "/default" );
         if  (exists) {
             System.out.println( "default name space init create succeed." );
         else  {
             System.out.println( "default name space init create failed." );
         }
 
         System.in.read();
 
         zkClient.close();
         zkServer.shutdown();
     }
}

 

  应用外部署server,使用client访问:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package  secondriver.dubbo.server;
 
import  org.I0Itec.zkclient.ZkClient;
 
import  java.util.List;
 
/**
  * Author : secondriver
  */
public  class  TestZkClient {
 
     public  static  void  main(String[] args) {
         //Only use client
         ZkClient zkc =  new  ZkClient( "192.168.88.153:2181,192.168.88.153:2182,192.168.88.153:2183" );
         List<String> childrens = zkc.getChildren( "/" );
         for  (String child : childrens) {
             System.out.println(child);
         }
     }
}

  

  下文代码示例使用adyliu/zkclient,同样依赖Zookeeper包,启动Zookeeper服务并做操作。

  maven adyliu/zkclient:

 

1
2
3
4
5
< dependency >
     < groupId >com.github.adyliu</ groupId >
     < artifactId >zkclient</ artifactId >
     < version >2.1.1</ version >
</ dependency >

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package  secondriver.dubbo.server;
 
import  com.github.zkclient.*;
 
import  java.io.IOException;
import  java.util.List;
 
/**
  * Author : secondriver
  */
public  class  TestZk {
 
 
     public  static  void  main(String[] args)  throws  IOException {
 
         String home = System.getProperty( "user.home" );
 
         //创建zookeeper服务并启动
         ZkServer zkServer =  new  ZkServer(home +  "/zookeeper/data" , home +  "/zookeeper/log" 2181 );
         zkServer.start();
 
         //方式一
//        ZkClient zkClient = new ZkClient("127.0.0.1:2181", 1000);
         //方式二
         ZkClient zkClient = zkServer.getZkClient();
 
         String path =  "/test"  + Math.random();
 
         //数据监听
         final  IZkDataListener dataListener =  new  IZkDataListener() {
             @Override
             public  void  handleDataChange(String dataPath,  byte [] data)  throws  Exception {
                 System.out.println(dataPath +  " data change" );
             }
 
             @Override
             public  void  handleDataDeleted(String dataPath)  throws  Exception {
 
             }
         };
 
         //结点(node)监听
         final  IZkChildListener childListener =  new  IZkChildListener() {
             @Override
             public  void  handleChildChange(String parentPath, List<String> currentChildren)  throws  Exception {
                 System.out.println(parentPath +  " parentPath" );
                 for  (String path : currentChildren) {
                     System.out.println(path);
                 }
             }
         };
 
         //为指定node添加监听
         zkClient.subscribeDataChanges(path, dataListener);
         zkClient.subscribeChildChanges( "/" , childListener);
 
         //zkclient操作Zookeeper服务
         ///检测node是否存在
         if  (zkClient.exists( "/zookeeper" )) {
             System.out.println( "Exist zookeeper path" );
         else  {
             System.out.println( "Not Exist zookeeper path" );
         }
 
         zkClient.createPersistent(path, path.getBytes());
         byte [] before = zkClient.readData(path);
         System.out.println( "before:"  new  String(before));
 
         //以原子的方式更新指定的path node的数据
         zkClient.cas(path,  new  IZkClient.DataUpdater() {
 
             @Override
             public  byte [] update( byte [] currentData) {
                 return  new  String(currentData).concat( new  String( " updated" )).getBytes();
             }
         });
 
         byte [] after = zkClient.readData(path);
         System.out.println( "after:"  new  String(after));
 
         //取消指定path node的数据监听
         zkClient.unsubscribeDataChanges(path, dataListener);
 
         zkClient.writeData(path,  "new-data" .getBytes());
 
         byte [] dataBytes = zkClient.readData(path);
         String data =  new  String(dataBytes);
         System.out.println(path +  " data :"  + data);
 
         System.in.read();
 
         zkClient.close();
         zkServer.shutdown();
     }
}


 3. Zookeeper客户端和富Zookeeper框架之curator



本文转自 secondriver 51CTO博客,原文链接:http://blog.51cto.com/aiilive/1684451,如需转载请自行联系原作者

相关文章
|
存储 API Apache
【zookeeper 第三篇章】客户端 API
本文介绍了Apache ZooKeeper客户端的一些常用命令及其用法。首先,`create`命令用于创建不同类型的节点并为其赋值,如持久化节点、有序节点及临时节点等。通过示例展示了如何创建这些节点,并演示了创建过程中的输出结果。其次,`ls`命令用于列出指定路径下的所有子节点。接着,`set`命令用于更新节点中的数据,可以指定版本号实现乐观锁机制。
270 0
|
消息中间件 监控 Ubuntu
大数据-54 Kafka 安装配置 环境变量配置 启动服务 Ubuntu配置 ZooKeeper
大数据-54 Kafka 安装配置 环境变量配置 启动服务 Ubuntu配置 ZooKeeper
453 3
大数据-54 Kafka 安装配置 环境变量配置 启动服务 Ubuntu配置 ZooKeeper
|
分布式计算 NoSQL Java
Hadoop-32 ZooKeeper 分布式锁问题 分布式锁Java实现 附带案例和实现思路代码
Hadoop-32 ZooKeeper 分布式锁问题 分布式锁Java实现 附带案例和实现思路代码
236 2
|
监控 Dubbo Java
dubbo学习三:springboot整合dubbo+zookeeper,并使用dubbo管理界面监控服务是否注册到zookeeper上。
这篇文章详细介绍了如何将Spring Boot与Dubbo和Zookeeper整合,并通过Dubbo管理界面监控服务注册情况。
1146 0
dubbo学习三:springboot整合dubbo+zookeeper,并使用dubbo管理界面监控服务是否注册到zookeeper上。
|
分布式计算 Java Hadoop
Hadoop-30 ZooKeeper集群 JavaAPI 客户端 POM Java操作ZK 监听节点 监听数据变化 创建节点 删除节点
Hadoop-30 ZooKeeper集群 JavaAPI 客户端 POM Java操作ZK 监听节点 监听数据变化 创建节点 删除节点
286 1
|
负载均衡 API 数据安全/隐私保护
Zookeeper的客户端-原生的API
Zookeeper的客户端-原生的API
|
Java Spring
spring cloud gateway在使用 zookeeper 注册中心时,配置https 进行服务转发
spring cloud gateway在使用 zookeeper 注册中心时,配置https 进行服务转发
523 3
【想进大厂还不会阅读源码】ShenYu源码-替换ZooKeeper客户端
ShenYu源码阅读。相信大家碰到源码时经常无从下手,不知道从哪开始阅读😭。我认为有一种办法可以解决大家的困扰!至此,我们发现自己开始从大量堆砌的源码中脱离开来😀。ShenYu是一个异步的,高性能的,跨语言的,响应式的 API 网关。
217 3
|
存储 大数据 Apache
深入理解ZooKeeper:分布式协调服务的核心与实践
【5月更文挑战第7天】ZooKeeper是Apache的分布式协调服务,确保大规模分布式系统中的数据一致性与高可用性。其特点包括强一致性、高可用性、可靠性、顺序性和实时性。使用ZooKeeper涉及安装配置、启动服务、客户端连接及执行操作。实际应用中,面临性能瓶颈、不可伸缩性和单点故障等问题,可通过水平扩展、集成其他服务和多集群备份来解决。理解ZooKeeper原理和实践,有助于构建高效分布式系统。
|
存储 Java Spring
使用Spring Boot和Zookeeper实现服务协调
使用Spring Boot和Zookeeper实现服务协调