2021年大数据ZooKeeper(五):ZooKeeper Java API操作
生活随笔
收集整理的這篇文章主要介紹了
2021年大数据ZooKeeper(五):ZooKeeper Java API操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
ZooKeeper?Java?API操作
引入maven坐標
節點的操作
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>
???????節點的操作
/*創建節點*/@Testpublic?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();}
總結
以上是生活随笔為你收集整理的2021年大数据ZooKeeper(五):ZooKeeper Java API操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021年大数据ZooKeeper(四)
- 下一篇: 2021年大数据ZooKeeper(六)