java 中 zookeeper簡單使用
一、zookeeper的基本原理
數(shù)據(jù)模型,如下:

ZooKeeper數(shù)據(jù)模型的結(jié)構(gòu)與Unix文件系統(tǒng)很類似,整體上可以看作是一棵樹,每個節(jié)點稱做一個ZNode。每個ZNode都可以通過其路徑唯一標識,比如上圖中第三層的第一個ZNode,它的路徑是/app1/c1。在每個ZNode上可存儲少量數(shù)據(jù)(默認是1M, 可以通過配置修改,通常不建議在ZNode上存儲大量的數(shù)據(jù)),這個特性非常有用。另外,每個ZNode上還存儲了其Acl信息,這里需要注意,雖說ZNode的樹形結(jié)構(gòu)跟Unix文件系統(tǒng)很類似,但是其Acl與Unix文件系統(tǒng)是完全不同的,每個ZNode的Acl的獨立的,子結(jié)點不會繼承父結(jié)點的。
ZooKeeper特性:
1、讀、寫(更新)模式
在ZooKeeper集群中,讀可以從任意一個ZooKeeperServer讀,這一點是保證ZooKeeper比較好的讀性能的關(guān)鍵;寫的請求會先Forwarder到Leader,然后由Leader來通過ZooKeeper中的原子廣播協(xié)議,將請求廣播給所有的Follower,Leader收到一半以上的寫成功的Ack后,就認為該寫成功了,就會將該寫進行持久化,并告訴客戶端寫成功了。
2、WAL和Snapshot
和大多數(shù)分布式系統(tǒng)一樣,ZooKeeper也有WAL(Write-Ahead-Log),對于每一個更新操作,ZooKeeper都會先寫WAL,然后再對內(nèi)存中的數(shù)據(jù)做更新,然后向Client通知更新結(jié)果。另外,ZooKeeper還會定期將內(nèi)存中的目錄樹進行Snapshot,落地到磁盤上,這個跟HDFS中的FSImage是比較類似的。這么做的主要目的,一當然是數(shù)據(jù)的持久化,二是加快重啟之后的恢復(fù)速度,如果全部通過ReplayWAL的形式恢復(fù)的話,會比較慢。
3、FIFO
對于每一個ZooKeeper客戶端而言,所有的操作都是遵循FIFO順序的,這一特性是由下面兩個基本特性來保證的:一是ZooKeeperClient與Server之間的網(wǎng)絡(luò)通信是基于TCP,TCP保證了Client/Server之間傳輸包的順序;二是ZooKeeperServer執(zhí)行客戶端請求也是嚴格按照FIFO順序的。
4、Linearizability
在ZooKeeper中,所有的更新操作都有嚴格的偏序關(guān)系,更新操作都是串行執(zhí)行的,這一點是保證ZooKeeper功能正確性的關(guān)鍵。
二、zookeeper的常用命令
我們可以執(zhí)行zookeeper-client或者執(zhí)行/opt/cloudera/parcels/CDH-5.0.0-1.cdh5.0.0.p0.47/lib/zookeeper/bin/zkCli.sh-server localhost,進入zookeeper命令行,如下:

然后,執(zhí)行l(wèi)s /可以看到:

然后,我們可以執(zhí)行create /qyktest‘qyktest'創(chuàng)建一個節(jié)點,如下:

然后,我們執(zhí)行g(shù)et /qyktest獲取節(jié)點值,如下:

然后,我們可以執(zhí)行set /qyktest‘111'修改節(jié)點的值,如下:

最后,我們執(zhí)行delete /qyktest便可刪除此節(jié)點。
另外,我們還可以在qyktest此節(jié)點下繼續(xù)創(chuàng)建子節(jié)點。
好了,幾個基本命令就講到這人啦,其它的命令還有很多,大家可以去查閱下資料。
三、zookeeper的javaapi操作
關(guān)于Javaapi操作zookeeper比較簡單,筆者直接貼出代碼,如下:
packageorg.zookeeper.demo;
importjava.io.IOException;
importjava.util.concurrent.CountDownLatch;
importorg.apache.zookeeper.CreateMode;
importorg.apache.zookeeper.KeeperException;
importorg.apache.zookeeper.WatchedEvent;
importorg.apache.zookeeper.Watcher;
importorg.apache.zookeeper.Watcher.Event.KeeperState;
importorg.apache.zookeeper.ZooDefs.Ids;
importorg.apache.zookeeper.ZooKeeper;
publicclassZookeeperClientimplementsWatcher{
//連接超時時間,10s
privatestaticfinalintSESSION_TIMEOUT= 10000;
//連接的zookeeperserver
privatestaticfinalStringCONNECTION_STRING = "172.31.25.8:2181";
privatestaticfinalStringZK_PATH = "/qyktest";
privateZooKeeperzk = null;
privateCountDownLatchconnectedSemaphore = newCountDownLatch(1);
publicvoidcreateConnection(StringconnectString, intsessionTimeout){
this.releaseConnection();
try{
zk= newZooKeeper(connectString,sessionTimeout, this);
connectedSemaphore.await();
}catch(InterruptedExceptione) {
System.out.println("連接創(chuàng)建失敗,發(fā)生InterruptedException");
e.printStackTrace();
}catch(IOExceptione) {
System.out.println("連接創(chuàng)建失敗,發(fā)生IOException");
e.printStackTrace();
}
}
publicvoidreleaseConnection(){
if(this.zk!= null){
try{
this.zk.close();
}catch(InterruptedExceptione) {
e.printStackTrace();
}
}
}
publicbooleancreatePath(Stringpath, String data) {
try{
Stringresult = this.zk.create(path,data.getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
System.out.println("節(jié)點創(chuàng)建成功,Path: "+result + ", content: "+data);
}catch(KeeperExceptione) {
System.out.println("節(jié)點創(chuàng)建失敗,發(fā)生KeeperException");
e.printStackTrace();
}catch(InterruptedExceptione) {
System.out.println("節(jié)點創(chuàng)建失敗,發(fā)生InterruptedException");
e.printStackTrace();
}
returntrue;
}
publicStringreadData(Stringpath) {
try{
System.out.println("獲取數(shù)據(jù)成功,path:"+path);
returnnewString(this.zk.getData(path,false,null));
}catch(KeeperExceptione) {
System.out.println("讀取數(shù)據(jù)失敗,發(fā)生KeeperException,path:"+path);
e.printStackTrace();
return"";
}catch(InterruptedExceptione) {
System.out.println("讀取數(shù)據(jù)失敗,發(fā)生InterruptedException,path: "+path);
e.printStackTrace();
return"";
}
}
publicbooleanwriteData(Stringpath, String data) {
try{
System.out.println("更新數(shù)據(jù)成功,path:"+path + ", stat: "+this.zk.setData(path,data.getBytes(), -1));
}catch(KeeperExceptione) {
System.out.println("更新數(shù)據(jù)失敗,發(fā)生KeeperException,path:"+path);
e.printStackTrace();
}catch(InterruptedExceptione) {
System.out.println("更新數(shù)據(jù)失敗,發(fā)生InterruptedException,path: "+path);
e.printStackTrace();
}
returnfalse;
}
publicvoiddeleteNode(Stringpath) {
try{
this.zk.delete(path,-1);
System.out.println("刪除節(jié)點成功,path:"+path);
}catch(KeeperExceptione) {
System.out.println("刪除節(jié)點失敗,發(fā)生KeeperException,path:"+path);
e.printStackTrace();
}catch(InterruptedExceptione) {
System.out.println("刪除節(jié)點失敗,發(fā)生InterruptedException,path: "+path);
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args) {
ZookeeperClientsample = newZookeeperClient();
//獲取連接
sample.createConnection(CONNECTION_STRING,SESSION_TIMEOUT);
//讀數(shù)據(jù)
Stringqyk = sample.readData("/qyktest");
System.out.println("qyk:"+qyk);
Stringurl = sample.readData("/qyk/db/url");
System.out.println("url"+url);
Stringdriver = sample.readData("/qyk/db/driver");
System.out.println("driver"+driver);
StringuserName = sample.readData("/qyk/db/userName");
System.out.println("userName"+userName);
Stringpassword = sample.readData("/qyk/db/password");
System.out.println("password"+password);
//創(chuàng)建節(jié)點
sample.createPath(ZK_PATH,"我是節(jié)點初始內(nèi)容");
System.out.println("數(shù)據(jù)內(nèi)容:"+sample.readData(ZK_PATH) + "\n");
//更新節(jié)點
sample.writeData(ZK_PATH,"更新后的數(shù)據(jù)");
System.out.println("數(shù)據(jù)內(nèi)容:"+sample.readData(ZK_PATH) + "\n");
//刪除節(jié)點
sample.deleteNode(ZK_PATH);
//釋放連接
sample.releaseConnection();
}
@Override
publicvoidprocess(WatchedEventevent) {
System.out.println("收到事件通知:"+event.getState() + "\n");
if(KeeperState.SyncConnected== event.getState()) {
connectedSemaphore.countDown();
}
}
}
然后,執(zhí)行可以看到,控制臺輸出如下:

所以,像一些公用的配置,我們可以存到zookeeper里面,之后其它的服務(wù)就可以使用了
總結(jié)
以上所述是小編給大家介紹的java 中 zookeeper簡單使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
RequestContextHolder.getRequestAttributes()空指針問題及解決
這篇文章主要介紹了RequestContextHolder.getRequestAttributes()空指針問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringBoot結(jié)合Vue實現(xiàn)投票系統(tǒng)過程詳解
這篇文章主要介紹了SpringBoot+Vue框架實現(xiàn)投票功能的項目系統(tǒng),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09
Java業(yè)務(wù)中臺確保數(shù)據(jù)一致性的解決方案
數(shù)據(jù)一致性通常指關(guān)聯(lián)數(shù)據(jù)之間的邏輯關(guān)系是否正確和完整。而數(shù)據(jù)存儲的一致性模型則可以認為是存儲系統(tǒng)和數(shù)據(jù)使用者之間的一種約定。如果使用者遵循這種約定,則可以得到系統(tǒng)所承諾的訪問結(jié)果2021-10-10
聊聊Spring?Cloud?Gateway過濾器精確控制異常返回問題
這篇文章主要介紹了Spring?Cloud?Gateway過濾器精確控制異常返回問題,本篇任務(wù)就是分析上述現(xiàn)象的原因,通過閱讀源碼搞清楚返回碼和響應(yīng)body生成的具體邏輯,需要的朋友可以參考下2021-11-11

