代碼::https://gitee.com/jly521/ZooKeeper-book.gitjava
開源的ZooKeeper 客戶端git
- 封裝了不少底層細節
- Apache 頂級項目
- 還提供了ZooKeeper各類應用場景:
- Recipe共享鎖服務
- Master選舉機制
- 分佈式計數器
- 等等
建立會話api
public static void main(String[] args) throws Exception{
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client =
CuratorFrameworkFactory.newClient("192.168.48.133:2181",
5000,
3000,
retryPolicy);
client.start();
Thread.sleep(Integer.MAX_VALUE);
}
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
- 使用Fluent風格的API接口來建立一個ZooKeeper客戶端
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
- guaranteed() 接口
- 客戶端碰到網絡異常的時候,會不停的重試刪除須要刪除的節點,知道成功
- 異步接口
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
Curator 典型應用場景:服務器
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
- Master 選舉
- 咱們常常遇到這樣的問題,遇到複雜的問題須要從集羣中選擇一臺進行處理
- 好比:多臺客戶端機器同時某節點建立相同本身節點,最終只有一臺能成功建立
- Curator進行了封裝,只須要簡單的api 就可實現Master 選舉
- 成功獲取Master 權力會回調監聽器
- 執行完takeLeadership 方法,會自動釋放Master 權力
![](http://static.javashuo.com/static/loading.gif)
- 分佈式鎖
- 分佈式環境中,爲了保證數據的一致性,常常在程序的某個運行點須要同步
- 好比減庫存操做或流水號生成操做
- 例如流水號:
- 普通的流水號生成使用時間戳,可是在併發量過大的狀況下會出現問題
- 可以使用Curator 實現分佈式鎖
- 分佈式計數器
- 很容易基於分佈式鎖實現一個分佈式計數器
- 分佈式Barrier
- 控制多線程之間同步的經典方式,類比jdk自帶的CyclicBarrier
- 等待全部線程準備就緒,一塊兒開始執行新的任務
- 還可協調同時進入同時退出
工具網絡
- ZKPaths
- 提供了一個簡單的API 來構建ZNode路徑、遞歸建立、刪除節點等;
- EnsurePath
- TestServer
- 爲了方便開發人員進行方便測試
- 提供啓動簡易ZooKeeper方法:TestServer
- 容許開發人員很是方便啓動一臺標準的ZooKeeper服務器,進行單元測試
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)