分布式框架Zookeeper?api的使用介紹
前言
Zookeeper API共包含五個包,分別為:
- org.apache.zookeeper
- org.apache.zookeeper.data
- org.apache.zookeeper.server
- org.apache.zookeeper.server.quorum
- org.apache.zookeeper.server.upgrade
其中org.apache.zookeeper,包含Zookeeper類,他是我們編程時最常?的類文件。這個類是Zookeeper客戶端的主要類文件。如果要使用Zookeeper服務,應?程序?先必須創(chuàng)建?個Zookeeper實例,這時就需要使用此類。?旦客戶端和Zookeeper服務端建立起了連接,Zookeeper系統(tǒng)將會給本次連接會話分配?個ID值,并且客戶端將會周期性的向服務器端發(fā)送心跳來維持會話連接。只要連接有效,客戶端就可以使?Zookeeper API來做相應處理了
導入依賴
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
</dependency>建立會話
package com.lagou.api;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class CreateSession implements Watcher {
private static CountDownLatch countDownLatch = new CountDownLatch(1);
/**
* 建立會話
*/
public static void main(String[] args) throws IOException, InterruptedException {
/*
客戶端可以通過創(chuàng)建?個zk實例來連接zk服務器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 連接地址:IP:端?
sesssionTimeOut:會話超時時間:單位毫秒
Wather:監(jiān)聽器(當特定事件觸發(fā)監(jiān)聽時,zk會通過watcher通知到客戶端)
*/
ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSession());
System.out.println(zooKeeper.getState());
// 計數(shù)工具類 CountDownLatch : 不讓main方法結(jié)束,讓線程處于等待阻塞
countDownLatch.await();
System.out.println("客戶端與服務端會話真正建立了");
}
/**
* 回調(diào)方法:處理來自服務器端的watcher通知
*/
// 當前類實現(xiàn)了Watcher接?,重寫了process?法,該?法負責處理來?Zookeeper服務端的watcher通知,在收到服務端發(fā)送過來的SyncConnected事件之后,解除主程序在CountDownLatch上的等待阻塞,?此,會話創(chuàng)建完畢
public void process(WatchedEvent watchedEvent) {
//當連接創(chuàng)建了,服務端發(fā)送給客戶端SyncConnected事件
if(watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 解除主程序在CountDownLatch上的等待阻塞
countDownLatch.countDown();
}
}
}注意,ZooKeeper 客戶端和服務端會話的建立是?個異步的過程,也就是說在程序中,構(gòu)造?法會在處理完客戶端初始化工作后立即返回,在?多數(shù)情況下,此時并沒有真正建立好?個可用的會話,在會話的生命周期中處于“CONNECTING”的狀態(tài)。當該會話真正創(chuàng)建完畢后ZooKeeper服務端會向會話對應的客戶端發(fā)送?個事件通知,以告知客戶端,客戶端只有在獲取這個通知之后,才算真正建立了會話。
創(chuàng)建節(jié)點
package com.lagou.api;
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class CreateNote implements Watcher {
private static ZooKeeper zooKeeper;
/**
* 建立會話
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
/*
客戶端可以通過創(chuàng)建?個zk實例來連接zk服務器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 連接地址:IP:端?
sesssionTimeOut:會話超時時間:單位毫秒
Wather:監(jiān)聽器(當特定事件觸發(fā)監(jiān)聽時,zk會通過watcher通知到客戶端)
*/
zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNote());
System.out.println(zooKeeper.getState());
Thread.sleep(Integer.MAX_VALUE);
}
// 創(chuàng)建節(jié)點的方法
private static void createNoteSync() throws InterruptedException, KeeperException {
/**
* path :節(jié)點創(chuàng)建的路徑
* data[] :節(jié)點創(chuàng)建要保存的數(shù)據(jù),是個byte類型的
* acl :節(jié)點創(chuàng)建的權限信息(4種類型)
* ANYONE_ID_UNSAFE : 表示任何?
* AUTH_IDS :此ID僅可?于設置ACL。它將被客戶機驗證的ID替換。
* OPEN_ACL_UNSAFE :這是?個完全開放的ACL(常?)--> world:anyone
* CREATOR_ALL_ACL :此ACL授予創(chuàng)建者身份驗證ID的所有權限
* createMode :創(chuàng)建節(jié)點的類型(4種類型)
* PERSISTENT:持久節(jié)點
* PERSISTENT_SEQUENTIAL:持久順序節(jié)點
* EPHEMERAL:臨時節(jié)點
* EPHEMERAL_SEQUENTIAL:臨時順序節(jié)點
String node = zookeeper.create(path,data,acl,createMode);
*/
// 持久節(jié)點
String note_persistent = zooKeeper.create("/lg-persistent", "持久節(jié)點內(nèi)容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 臨時節(jié)點
String note_ephemeral = zooKeeper.create("/lg-ephemeral", "臨時節(jié)點內(nèi)容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// 持久順序節(jié)點
String note_sequential = zooKeeper.create("/lg-sequential", "持久順序節(jié)點內(nèi)容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println("創(chuàng)建的持久節(jié)點: " + note_persistent);
System.out.println("創(chuàng)建的臨時節(jié)點: " + note_ephemeral);
System.out.println("創(chuàng)建的持久順序節(jié)點: " + note_sequential);
}
/**
* 回調(diào)方法:處理來自服務器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 創(chuàng)建節(jié)點
try {
createNoteSync();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}獲取節(jié)點數(shù)據(jù)
package com.lagou.api;
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.List;
public class GetNoteData implements Watcher {
private static ZooKeeper zooKeeper;
/**
* 建立會話
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
/*
客戶端可以通過創(chuàng)建?個zk實例來連接zk服務器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 連接地址:IP:端?
sesssionTimeOut:會話超時時間:單位毫秒
Wather:監(jiān)聽器(當特定事件觸發(fā)監(jiān)聽時,zk會通過watcher通知到客戶端)
*/
zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new GetNoteData());
System.out.println(zooKeeper.getState());
Thread.sleep(Integer.MAX_VALUE);
}
/**
* 回調(diào)方法:處理來自服務器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
/*
子節(jié)點列表發(fā)生改變時,服務端會發(fā)送noteChildrenChanged事件通知
要重新獲取子節(jié)點列表,同時注意:通知是一次性的,需要反復注冊監(jiān)聽
*/
if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
List<String> children = null;
try {
children = zooKeeper.getChildren("/lg-persistent", true);
} catch (KeeperException | InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(children);
}
// SyncConnected
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 獲取節(jié)點數(shù)據(jù)的方法
try {
getNoteData();
// 獲取節(jié)點的子節(jié)點列表方法
getChildren();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/*
獲取某個節(jié)點的內(nèi)容
*/
private void getNoteData() throws Exception {
/**
* path : 獲取數(shù)據(jù)的路徑
* watch : 是否開啟監(jiān)聽
* stat : 節(jié)點狀態(tài)信息
* null: 表示獲取最新版本的數(shù)據(jù)
* zk.getData(path, watch, stat);
*/
byte[] data = zooKeeper.getData("/lg-persistent", false, null);
System.out.println(new String(data));
}
/*
獲取某個節(jié)點的子節(jié)點列表方法
*/
public static void getChildren() throws InterruptedException, KeeperException {
/*
path:路徑
watch:是否要啟動監(jiān)聽,當?節(jié)點列表發(fā)?變化,會觸發(fā)監(jiān)聽
zooKeeper.getChildren(path, watch);
*/
List<String> children = zooKeeper.getChildren("/lg-persistent", true);
System.out.println(children);
}
}修改節(jié)點數(shù)據(jù)
package com.lagou.api;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
public class UpdateNoteData implements Watcher {
private static ZooKeeper zooKeeper;
/**
* 建立會話
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
/*
客戶端可以通過創(chuàng)建?個zk實例來連接zk服務器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 連接地址:IP:端?
sesssionTimeOut:會話超時時間:單位毫秒
Wather:監(jiān)聽器(當特定事件觸發(fā)監(jiān)聽時,zk會通過watcher通知到客戶端)
*/
zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new UpdateNoteData());
System.out.println(zooKeeper.getState());
Thread.sleep(Integer.MAX_VALUE);
}
/**
* 回調(diào)方法:處理來自服務器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 更新數(shù)據(jù)節(jié)點內(nèi)容的方法
try {
updateNoteSync();
} catch (InterruptedException | KeeperException e) {
throw new RuntimeException(e);
}
}
}
/*
更新數(shù)據(jù)節(jié)點內(nèi)容的方法
*/
private void updateNoteSync() throws InterruptedException, KeeperException {
/*
path:路徑
data:要修改的內(nèi)容 byte[]
version:為-1,表示對最新版本的數(shù)據(jù)進?修改
zooKeeper.setData(path, data,version);
*/
byte[] data = zooKeeper.getData("/lg-persistent", false, null);
System.out.println("修改前的值:" + new String(data));
// 修改 /lg-persistent 的數(shù)據(jù) stat: 狀態(tài)信息對象
Stat stat = zooKeeper.setData("/lg-persistent", "客戶端修改了節(jié)點數(shù)據(jù)".getBytes(), -1);
byte[] data2 = zooKeeper.getData("/lg-persistent", false, null);
System.out.println("修改后的值:" + new String(data2));
}
}刪除節(jié)點
package com.lagou.api;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
public class DeleteNote implements Watcher {
private static ZooKeeper zooKeeper;
/**
* 建立會話
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
/*
客戶端可以通過創(chuàng)建?個zk實例來連接zk服務器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 連接地址:IP:端?
sesssionTimeOut:會話超時時間:單位毫秒
Wather:監(jiān)聽器(當特定事件觸發(fā)監(jiān)聽時,zk會通過watcher通知到客戶端)
*/
zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new DeleteNote());
System.out.println(zooKeeper.getState());
Thread.sleep(Integer.MAX_VALUE);
}
/**
* 回調(diào)方法:處理來自服務器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 刪除節(jié)點
try {
deleteNoteSync();
} catch (InterruptedException | KeeperException e) {
throw new RuntimeException(e);
}
}
}
/*
刪除節(jié)點方法
*/
private void deleteNoteSync() throws InterruptedException, KeeperException {
/*
zooKeeper.exists(path,watch) :判斷節(jié)點是否存在
zookeeper.delete(path,version) : 刪除節(jié)點
*/
Stat stat = zooKeeper.exists("/lg-persistent/c1", false);
System.out.println(stat == null ? "該節(jié)點不存在" : "該節(jié)點存在");
if (stat != null) {
zooKeeper.delete("/lg-persistent/c1", -1);
}
Stat stat2 = zooKeeper.exists("/lg-persistent/c1", false);
System.out.println(stat2 == null ? "該節(jié)點不存在" : "該節(jié)點存在");
}
}到此這篇關于分布式框架Zookeeper api的使用介紹的文章就介紹到這了,更多相關Zookeeper api內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java 基于TCP Socket 實現(xiàn)文件上傳
這篇文章主要介紹了Java 基于TCP Socket 實現(xiàn)文件上傳的示例代碼,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12
SpringCloudGateway 網(wǎng)關登錄校驗實現(xiàn)思路
文章介紹了在微服務架構(gòu)中使用Spring Cloud Gateway進行登錄校驗的方法,通過在網(wǎng)關層面進行登錄校驗,并將用戶信息通過請求頭傳遞給下游微服務,解決了每個微服務都需要獨立進行登錄校驗的問題,此外,還討論了如何在微服務之間傳遞用戶信息2024-11-11
maven插件maven-assembly-plugin打包歸納文件zip/tar使用
java項目運行的文件需要jar或者war格式,同時還需要使用Java命令,本文主要介紹了maven插件maven-assembly-plugin打包歸納文件zip/tar使用,具有一定的參考價值,感興趣的可以了解一下2024-02-02

