ZK的Java客户端Curator(6)
实践6 认证授权
1.递归权限
- creatingParentsIfNeeded():父节点不存在。递归创建节
- CreateMode.PERSISTENT:递归创建
- withACL()设置节点权限
- withACL(acls, true) 递归设置节点权限
// 实例化
CuratorAcl cto = new CuratorAcl();
boolean isZkCuratorStarted = cto.client.isStarted();
System.out.println("当前客户的状态:" + (isZkCuratorStarted ? "连接中" : "已关闭"));
String nodePath = "/acl/father/child/sub";
List<ACL> acls = new ArrayList<ACL>();
Id imooc1 = new Id("digest", AclUtils.getDigestUserPwd("imooc1:123456"));
Id imooc2 = new Id("digest", AclUtils.getDigestUserPwd("imooc2:123456"));
acls.add(new ACL(Perms.ALL, imooc1));
acls.add(new ACL(Perms.READ, imooc2));
acls.add(new ACL(Perms.DELETE | Perms.CREATE, imooc2));
// 创建节点
byte[] data = "spiderman".getBytes();
cto.client.create().creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.withACL(acls, true)
.forPath(nodePath, data);
2.设置单节点权限
如果想修改已有节点的权限,可以使用下面方法:
cto.client.setACL().withACL(acls).forPath("/curatorNode");
3.创建时授权
创建时授权才可以递归对节点创建授权
父节点授权时,用户默认权限没办法访问这个节点,所以需要授权
RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
client = CuratorFrameworkFactory.builder().authorization("digest", "imooc:123456".getBytes())
.connectString(zkServerPath)
.sessionTimeoutMs(10000).retryPolicy(retryPolicy)
.namespace("workspace").build();
client.start();
4.测试权限
// 更新节点数据
byte[] newData = "batman".getBytes();
cto.client.setData().withVersion(0).forPath(nodePath, newData);
初始化使用用户imooc授权,对节点修改数据会报错:no Auth
切换为imooc用户可以正常进行修改