Zookeeper
原生API的實現
- 連接Zookeeper
/**
* @Author: zxx
* @Date: 2020/3/30 20:43
* @Description: 連接zookeeper
*/
public class ZKConnection {
@Test
public void zkconnect() throws IOException, InterruptedException {
String ip="192.168.21.141:2181";
// 計數器對象
final CountDownLatch countDownLatch=new CountDownLatch(1);
// 連接對象
ZooKeeper zooKeeper=new ZooKeeper(ip, 5000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
try {
//EventType = None時
if (watchedEvent.getType() == Watcher.Event.EventType.None) {
if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
System.out.println("連接成功");
countDownLatch.countDown();
} else if (watchedEvent.getState() == Watcher.Event.KeeperState.Disconnected) {
System.out.println("斷開連接");
} else if (watchedEvent.getState() == Watcher.Event.KeeperState.Expired) {
System.out.println("會話超時");
} else if (watchedEvent.getState() == Watcher.Event.KeeperState.AuthFailed) {
System.out.println("認證失敗");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
countDownLatch.await();
zooKeeper.close();
}
}
- 創建節點
// 同步方式
create(String path, byte[] data, List<ACL> acl, CreateMode createMode)
// 異步方式
create(String path, byte[] data, List<ACL> acl, CreateMode createMode, AsyncCallback.StringCallback callBack,Object ctx)
path - znode路徑。例如,/node1 /node1/node11
data - 要存儲在指定znode路徑中的數據
acl - 要創建的節點的訪問控制列表。zookeeper API提供了一個靜態接口
ZooDefs.Ids 來獲取一些基本的acl列表。例如,ZooDefs.Ids.OPEN_ACL_UNSAFE 返回打開znode的acl列表。 createMode - 節點的類型,這是一個枚舉。
callBack-異步回調接口
ctx-傳遞上下文參數
/**
* @Author: zxx
* @Date: 2020/3/30 20:49
* @Description: 新增節點
*/
public class ZKCreate {
private String IP = "192.168.21.141:2181";
public static ZooKeeper zooKeeper;
//連接zookeeper
@Before
public void before() throws InterruptedException, IOException {
final CountDownLatch countDownLatch=new CountDownLatch(1);
zooKeeper = new ZooKeeper(IP, 6000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
countDownLatch.countDown();
}
System.out.println("path=" + watchedEvent.getPath());
System.out.println("eventType=" + watchedEvent.getType());
}
});
countDownLatch.await();
}
@After
public void after() throws InterruptedException {
zooKeeper.close();
}
@Test
public void zkCreate1() throws KeeperException, InterruptedException {
zooKeeper.create("/node1", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
@Test
public void zkCreate2() throws KeeperException, InterruptedException {
zooKeeper.create("/node1", "data".getBytes(), ZooDefs.Ids.READ_ACL_UNSAFE,CreateMode.PERSISTENT);
}
@Test
public void zkCreate3() throws KeeperException, InterruptedException {
List<ACL> acls = new ArrayList<ACL>();
//授權模式和對象
Id id = new Id("world", "anyone");
acls.add(new ACL(ZooDefs.Perms.READ, id));
acls.add(new ACL(ZooDefs.Perms.CREATE, id));
zooKeeper.create("/node1", "data".getBytes(), acls,CreateMode.PERSISTENT);
}
@Test
public void zkCreate4() throws KeeperException, InterruptedException {
//auth授權
zooKeeper.addAuthInfo("digest", "username:123456".getBytes());
zooKeeper.create("/node1", "data".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL,CreateMode.PERSISTENT);
}
@Test
public void zkCreate5() throws Exception {
// 持久化順序節點
// Ids.OPEN_ACL_UNSAFE world:anyone:cdrwa
String result = zooKeeper.create("/create/node1", "node1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println(result);
}
}
- 更新節點
// 同步方式
setData(String path, byte[] data, int version)
// 異步方式
setData(String path, byte[] data, int version,AsyncCallback.StatCallback callBack, Object ctx)
path- znode路徑
data - 要存儲在指定znode路徑中的數據。
version- znode的當前版本。每當數據更改時,ZooKeeper會更新znode的版本號。
callBack-異步回調接口 ctx-傳遞上下文參數
/**
* @Author: zxx
* @Date: 2020/3/30 20:49
* @Description: 更新節點
*/
public class ZKUpdate {
private String IP = "192.168.21.141:2181";
public static ZooKeeper zooKeeper;
//連接zookeeper
@Before
public void before() throws InterruptedException, IOException {
final CountDownLatch countDownLatch=new CountDownLatch(1);
zooKeeper = new ZooKeeper(IP, 6000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
countDownLatch.countDown();
}
System.out.println("path=" + watchedEvent.getPath());
System.out.println("eventType=" + watchedEvent.getType());
}
});
countDownLatch.await();
}
@After
public void after() throws InterruptedException {
zooKeeper.close();
}
@Test
public void zkCreate1() throws KeeperException, InterruptedException {
// arg1:節點的路徑
// arg2:節點的數據
// arg3:版本號 -1代表版本號不作爲修改條件
Stat stat=zooKeeper.setData("/node1","nodedata".getBytes(),2);
// 節點的版本號
System.out.println(stat.getVersion());
// 節點的創建時間
System.out.println(stat.getCtime());
}
@Test
public void zkCreate2() throws KeeperException, InterruptedException {
// 異步方式修改節點
zooKeeper.setData("/node2", "node2".getBytes(), -1, new AsyncCallback.StatCallback() {
public void processResult(int rc, String path, Object ctx, Stat stat) {
// 0 代表修改成功
System.out.println(rc);
// 修改節點的路徑
System.out.println(path);
// 上線文的參數對象
System.out.println(ctx);
// 版本信息
System.out.println(stat.getVersion());
} },"I am Context");
Thread.sleep(50000);
System.out.println("結束");
}
}
- 刪除節點
// 同步方式
delete(String path, int version)
// 異步方式
delete(String path, int version, AsyncCallback.VoidCallback callBack, Object ctx)
path - znode路徑。
version - znode的當前版本
callBack-異步回調接口
ctx-傳遞上下文參數
public class ZKDelete {
String IP = "192.168.21.141:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception {
final CountDownLatch countDownLatch = new CountDownLatch(1);
// arg1:zookeeper服務器的ip地址和端口號
// arg2:連接的超時時間 以毫秒爲單位
// arg3:監聽器對象
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("連接創建成功!");
countDownLatch.countDown();
}
}
});
// 使主線程阻塞等待
countDownLatch.await();
}
@After
public void after() throws Exception {
zooKeeper.close();
}
@Test
public void delete1() throws Exception {
// arg1:刪除節點的節點路徑
// arg2:數據版本信息 -1代表刪除節點時不考慮版本信息
zooKeeper.delete("/delete/node1",-1);
}
@Test
public void delete2() throws Exception {
// 異步使用方式
zooKeeper.delete("/delete/node2", -1, new AsyncCallback.VoidCallback() {
public void processResult(int rc, String path, Object ctx) {
// 0代表刪除成功
System.out.println(rc);
// 節點的路徑
System.out.println(path);
// 上下文參數對象
System.out.println(ctx);
}
},"I am Context");
Thread.sleep(10000);
System.out.println("結束");
}
}
- 查看節點
// 同步方式
getData(String path, boolean b, Stat stat)
// 異步方式
getData(String path, boolean b,AsyncCallback.DataCallback callBack, Object ctx)
path - znode路徑。
b- 是否使用連接對象中註冊的監視器。
stat - 返回znode的元數據。
callBack-異步回調接口
ctx-傳遞上下文參數
public class ZKGet {
String IP = "192.168.21.141:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception {
final CountDownLatch countDownLatch = new CountDownLatch(1);
// arg1:zookeeper服務器的ip地址和端口號
// arg2:連接的超時時間 以毫秒爲單位
// arg3:監聽器對象
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("連接創建成功!");
countDownLatch.countDown();
}
}
});
// 使主線程阻塞等待
countDownLatch.await();
}
@After
public void after() throws Exception {
zooKeeper.close();
}
@Test
public void get1() throws Exception {
// arg1:節點的路徑
// arg3:讀取節點屬性的對象
Stat stat=new Stat();
byte [] bys=zooKeeper.getData("/get/node1",false,stat);
// 打印數據
System.out.println(new String(bys));
// 版本信息
System.out.println(stat.getVersion());
}
@Test
public void get2() throws Exception {
//異步方式
zooKeeper.getData("/get/node1", false, new AsyncCallback.DataCallback() {
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
// 0代表讀取成功
System.out.println(rc);
// 節點的路徑
System.out.println(path);
// 上下文參數對象
System.out.println(ctx);
// 數據
System.out.println(new String(data));
// 屬性對象
System.out.println(stat.getVersion());
}
},"I am Context");
Thread.sleep(10000);
System.out.println("結束");
}
}
- 查看子節點
// 同步方式
getChildren(String path, boolean b)
// 異步方式
getChildren(String path, boolean b,AsyncCallback.ChildrenCallback callBack,Object ctx)
path - Znode路徑。
b- 是否使用連接對象中註冊的監視器。
callBack - 異步回調接口。
ctx-傳遞上下文參數
public class ZKGetChid {
String IP = "192.168.21.141:2181";
ZooKeeper zooKeeper;
@Before
public void before() throws Exception {
final CountDownLatch countDownLatch = new CountDownLatch(1);
// arg1:zookeeper服務器的ip地址和端口號
// arg2:連接的超時時間 以毫秒爲單位
// arg3:監聽器對象
zooKeeper = new ZooKeeper(IP, 5000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("連接創建成功!");
countDownLatch.countDown();
}
}
});
// 使主線程阻塞等待
countDownLatch.await();
}
@After
public void after() throws Exception {
zooKeeper.close();
}
@Test
public void get1() throws Exception {
// arg1:節點的路徑
List<String> list = zooKeeper.getChildren("/get", false);
for (String str : list) {
System.out.println(str);
}
}
@Test
public void get2() throws Exception {
// 異步用法
zooKeeper.getChildren("/get", false, new AsyncCallback.ChildrenCallback() {
public void processResult(int rc, String path, Object ctx, List<String> children) {
// 0代表讀取成功
System.out.println(rc);
// 節點的路徑
System.out.println(path);
// 上下文參數對象
System.out.println(ctx);
// 子節點信息
for (String str : children) {
System.out.println(str);
}
}
},"I am Context");
Thread.sleep(10000);
System.out.println("結束");
}
}