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权限控制,节点为永久性的(即客户端shutdown了也不会消失)
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调用及权限控制