ACL机制是zookeeper用来实现对数据节点进行权限控制的机制,类似于Unix/linux的ACL,但又不完全相同。zookeeper的权限控制是由三方面来组成的,即权限模式(Scheme),授权对象(ID),权限(Permission),用“scheme:ID:permission”来标示一个有效的ACL信息。
//设置ip权限,允许特定的IP访问zookeeper的节点
@Test
public void setACL() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
Id id=new Id("ip","192.168.175.0/16");
ACL acl=new ACL(ZooDefs.Perms.READ,id);
List aclList=new ArrayList();
aclList.add(acl);
zooKeeper.create("/ip","ip schema".getBytes(),aclList, CreateMode.PERSISTENT);
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
@Test
public void getData() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
byte[] datas=zooKeeper.getData("/ip",null,null);
System.out.println(new String(datas,0,datas.length));
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
//设置zookeeper数据节点的权限
@Test
public void setACLDigest() throws IOException, KeeperException, InterruptedException, NoSuchAlgorithmException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
//第一种方法
Id id=new Id("digest", DigestAuthenticationProvider.generateDigest("lidihao:123"));
ACL acl=new ACL(ZooDefs.Perms.READ,id);
List aclList=new ArrayList();
aclList.add(acl);
zooKeeper.create("/digest1","digest schema".getBytes(),aclList, CreateMode.PERSISTENT);
//第二种方法
zookeeper.addAuth("digest","lidihao:123".getBytes());
zooKeeper.create("/digest1","digest schema".getBytes(),Ids.CREATEOR_ALL_ACL, CreateMode.PERSISTENT);
//第二种方法不用将密码加密
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
@Test
public void getDataDigest() throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=new ZooKeeper("192.168.175.130:2181,192.168.175.129:2181,192.168.175.133:2181",5000,null);
zooKeeper.addAuthInfo("digest","lidihao:123".getBytes());
byte[] datas=zooKeeper.getData("/digest1",null,null);
System.out.println(new String(datas,0,datas.length));
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}