1. 程式人生 > >zookeeper java調用及權限控制

zookeeper java調用及權限控制

刪除 proc ide class shee node 版本號 .cn nim


import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

/**
?* @author Keeny (2013-12-31)
?**/
public class Test {
?? ?public static void main(String[] args) throws IOException, KeeperException, InterruptedException, NoSuchAlgorithmException {
?? ??? ?ZooKeeper zk = new ZooKeeper("192.168.192.142:2181", 500000, new Watcher() {
?? ??? ??? ?// 監控全部被觸發的事件
?? ??? ??? ?public void process(WatchedEvent event) {
?? ??? ??? ??? ?System.out.println("WatchedEvent=" + event.toString());
?? ??? ??? ??? ?// dosomething
?? ??? ??? ?}
?? ??? ?});
?? ??? ?// 創建一個節點root,數據是mydata,不進行ACL權限控制,節點為永久性的(即clientshutdown了也不會消失)

?? ??? ?
?? ??? ?List<ACL> acls = new ArrayList<ACL>(2);??? ?
?? ??? ?Id id1 = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin123")); ?
?? ??? ?ACL acl1 = new ACL(ZooDefs.Perms.ALL, id1); ?
?? ??? ? ?
?? ??? ?Id id2 = new Id("digest", DigestAuthenticationProvider.generateDigest("guest:guest123")); ?
?? ??? ?ACL acl2 = new ACL(ZooDefs.Perms.READ, id2); ?
?? ??? ? ?
?? ??? ?acls.add(acl1); ?
?? ??? ?acls.add(acl2);? //設置權限
?? ??? ?
//?? ??? ?String root = zk.create("/root/test1", "test".getBytes(), acls, CreateMode.PERSISTENT);
//?? ??? ?System.out.println("root=" + root);

?? ??? ?// 在root以下創建一個childone znode,數據為childone,不進行ACL權限控制,節點為永久性的
?? ??? ?// String childone = zk.create("/root/childone", "childone".getBytes(),
?? ??? ?// Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
?? ??? ?// System.out.println("childone=" + childone);

?? ??? ?// 取得/root節點下的子節點名稱,返回List<String>
?? ??? ?zk.addAuthInfo("digest", "admin:chinatetadmin1234".getBytes());?? //設置權限
?? ??? ?
?? ??? ?List<String> lsit = zk.getChildren("/root", true);
?? ??? ?for (String string : lsit) {
?? ??? ??? ?System.out.println("節點:" + string);
?? ??? ?}

?? ??? ?// 取得/root/childone節點下的數據,返回byte[]
?? ??? ? byte[] childoneData = zk.getData("/root/msg", true, null);
?? ??? ? System.out.println("childoneData=" + new String(childoneData));

?? ??? ?// 改動節點/root/childone下的數據,第三個參數為版本號,假設是-1。那會無視被改動的數據版本號。直接改掉
?? ??? ?// zk.setData("/root/childone", "childonemodify".getBytes(), -1);

//?? ??? ? 刪除/root/childone這個節點,第二個參數為版本號,-1的話直接刪除,無視版本號
//?? ??? ? zk.delete("/root/msg", -1);
?? ??? ?//
?? ??? ?// zk.delete("/root/msg", -1);
?? ??? ?// 關閉session
?? ??? ?zk.close();
?? ?}
}


zookeeper java調用及權限控制