大数据ZooKeeper(五):ZooKeeper Java API操作
ZooKeeper Java API操作
这里操作Zookeeper的JavaAPI使用的是一套zookeeper客户端框架 Curator ,解决了很多Zookeeper客户端非常底层的细节开发工作 。
Curator包含了几个包:
curator-framework:对zookeeper的底层api的一些封装
curator-recipes:封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式计数器等
Maven依赖(使用curator的版本:2.12.0,对应Zookeeper的版本为:3.4.x,如果跨版本会有兼容性问题,很有可能导致节点操作失败):
引入maven坐标
- <dependencies>
-
- <dependency>
-
- <groupId>org.apache.curator</groupId>
-
- <artifactId>curator-framework</artifactId>
-
- <version>2.12.0</version>
-
- </dependency>
-
-
-
- <dependency>
-
- <groupId>org.apache.curator</groupId>
-
- <artifactId>curator-recipes</artifactId>
-
- <version>2.12.0</version>
-
- </dependency>
-
-
-
- <dependency>
-
- <groupId>com.google.collections</groupId>
-
- <artifactId>google-collections</artifactId>
-
- <version>1.0</version>
-
- </dependency>
-
- <dependency>
-
- <groupId>junit</groupId>
-
- <artifactId>junit</artifactId>
-
- <version>RELEASE</version>
-
- </dependency>
-
- <dependency>
-
- <groupId>org.slf4j</groupId>
-
- <artifactId>slf4j-simple</artifactId>
-
- <version>1.7.25</version>
-
- </dependency>
-
- </dependencies>
-
-
-
- <build>
-
- <plugins>
-
- <!-- java编译插件 -->
-
- <plugin>
-
- <groupId>org.apache.maven.plugins</groupId>
-
- <artifactId>maven-compiler-plugin</artifactId>
-
- <version>3.2</version>
-
- <configuration>
-
- <source>1.8</source>
-
- <target>1.8</target>
-
- <encoding>UTF-8</encoding>
-
- </configuration>
-
- </plugin>
-
- </plugins>
-
- </build>
节点的操作
- /*
-
- 创建节点
-
- */
-
- @Test
-
- public void createZnode() throws Exception {
-
- //1:定制一个重试策略
-
- /*
-
- param1: 重试的间隔时间
-
- param2:重试的最大次数
-
- */
-
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,1);
-
- //2:获取一个客户端对象
-
- /*
-
- param1:要连接的Zookeeper服务器列表
-
- param2:会话的超时时间
-
- param3:链接超时时间
-
- param4:重试策略
-
- */
-
- String connectionStr = "192.168.88.161:2181,192.168.88.162:2181,192.168.88.163:2181";
-
- CuratorFramework client = CuratorFrameworkFactory.newClient(connectionStr, 8000, 8000, retryPolicy);
-
-
-
- //3:开启客户端
-
- client.start();
-
- //4:创建节点
-
- /*
-
- 节点类型:
-
- CreateMode.PERSISTENT:永久节点
-
- CreateMode.PERSISTENT_SEQUENTIAL:永久序列化节点
-
- CreateMode.EPHEMERAL:临时节点
-
- CreateMode.EPHEMERAL_SEQUENTIAL:临时序列化节点
-
- /hello2 :节点路径
-
- world :节点数据
-
- */
-
- client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/hello2","world".getBytes());
-
- //5:关闭客户端
-
- client.close();
-
- }