手机版
你好,游客 登录 注册
背景:
阅读新闻

ZooKeeper客户端编程入门

[日期:2012-09-28] 来源:Linux社区  作者:tqtuuuu [字体:大 中 小]

ZooKeeper支持的权限:
CREATE: you can create a child node
READ: you can get data from a node and list its children.
WRITE: you can set data for a node
DELETE: you can delete a child node
ADMIN: you can set permissions

ZooKeeper内建的sheme:(scheme是ID的其中一个属性)
world has a single id, anyone, that represents anyone.
auth doesn't use any id, represents any authenticated user.
digest uses a username:password string to generate MD5 hash which is then used as an ACL ID identity. Authentication is done by sending theusername:password in clear text. When used in the ACL the expression will be the username:base64 encoded SHA1 password digest.
ip uses the client host IP as an ACL ID identity. The ACL expression is of the form addr/bits where the most significant bits of addr are matched against the most significant bits of the client host IP.

ZK内建的ID:
ANYONE_ID_UNSAFE    //任意用户
AUTH_IDS     //通过Auth认证过的用户

内建的权限控制集合:
OPEN_ACL_UNSAFE: 创建任何人都可以操作的节点
READ_ACL_UNSAFE: 创建任何人都可以读的节点
CREATOR_ALL_ACL: 设置了Auth的用户可以使用该ACL集合创建节点,该节点也只能被同样Auth授权的用户操作

示例代码如下:

  1. @Test  
  2.     public void testACL_with_ip_scheme() {  
  3.         try {  
  4.             Id id = new Id();  
  5.             id.setScheme("ip");  
  6.             id.setId(InetAddress.getLocalHost().getHostAddress());  
  7.               
  8.             ACL acl = new ACL();  
  9.             acl.setId(id);    //对ID所指定的目标设置权限   
  10.             acl.setPerms(Perms.ALL);  
  11.               
  12.             List<ACL> acls = new ArrayList<ACL>();  
  13.             acls.add(acl);    //可以添加多个运行的IP地址   
  14.               
  15.             String p = "/ip";  
  16.               
  17.             zk.create(p, p.getBytes(), acls, CreateMode.PERSISTENT);  
  18.               
  19.             zk.delete(p, -1);  //仅IP相同的用户可以对该进行进行操作   
  20.         } catch(Exception ex) {  
  21.             ex.printStackTrace();  
  22.         }  
  23.     }  

Watcher
可以设置Watcher的方式:
1) 在ZooKeeper的构造函数中可以设置Watcher

2) 使用ZooKeeper.register(Watcher)显示的更改在构造函数中设置的默认Watcher

3) 通过某些方法的调用可以更改某个path对应节点的Watcher?   

具体可以设置Watcher的方法如下所示:

1)     构造函数: state changes or node events

2)     Register: 修改构造函数中指定的默认Watcher.

3)     getData: triggered by sets data on the node, or deletes the node.

4)     getChildren: triggered by deletes the node or creates/delete a child under the node.

5)     exists: triggered by creates/delete the node or sets the data on the node.

其中构造函数阶段指定的Watcher一直有效(register方式属于该类),其余方法设置的Watcher仅有效一次。在方法调用时,如果指定开启watcher,如果该节点通过getData、getChildren和exists设置了Watcher,就触发该Watcher,然后使得该Watcher失效(但默认的Watcher还一直生效),否则触发构造函数中设定的默认Watcher。

示例代码如下:

  1. class ExistsWatcher implements Watcher {   
  2.    @Override  
  3.         public void process(WatchedEvent event) {  
  4.      System.out.println("---------------------------");  
  5.      System.out.println("setting by exist watcher");  
  6.      System.out.println("path is : " + event.getPath());  
  7.      System.out.println("type is : " + event.getType());  
  8.      System.out.println("state is : " + event.getState());  
  9.      System.out.println("---------------------------");  
  10.   }  
  11.  }  
  12. class DefaultWatcher implements Watcher {  
  13.   @Override  
  14.   public void process(WatchedEvent event) {  
  15.     System.out.println("=====>Default Watch Event: " + event.getType());  
  16.   }  
  17. }  
  18. @Test  
  19.   public void testWatcher() {  
  20.     try {  
  21.       DefaultWatcher defaultWatcher = new DefaultWatcher();  
  22.       ExistsWatcher existsWatcher = new ExistsWatcher();  
  23.       String p = "/watcher";  
  24.       ZooKeeper zk = new ZooKeeper(hostport, 300000, null);  
  25.       zk.register(defaultWatcher);  
  26.       Stat stat = zk.exists(p, existsWatcher);  
  27.       zk.create(p, p.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);  
  28.       stat = zk.exists(p, true);  
  29.       byte[] b = zk.getData(p, true, stat);  
  30.       System.out.println(new String(b));  
  31.       stat = zk.exists(p, true);  
  32.       zk.setData(p, "Iloveyou".getBytes(), stat.getVersion());  
  33.       stat = zk.exists(p, existsWatcher);  
  34.       zk.delete(p, stat.getVersion());  
  35.       zk.close();  
  36.     } catch(Exception ex) {  
  37.       ex.printStackTrace();  
  38.     }  
  39.   }  

运行结果如下:

  1. =====>Default Watch Event: None  
  2. ---------------------------                        
  3. setting by exist watcher  
  4. path is : /watcher  
  5. type is : NodeCreated  
  6. state is : SyncConnected  
  7. ---------------------------  
  8. /watcher  
  9. =====>Default Watch Event: NodeDataChanged  
  10. ---------------------------  
  11. setting by exist watcher  
  12. path is : /watcher  
  13. type is : NodeDeleted  
  14. state is : SyncConnected  
  15. ---------------------------  

异步调用
顾名思义,异步调用是指在调用某个方法后不等待其返回,而是接着处理下面的任务,当方法调用完成时触发某个回调函数,回调函数需要在方法调用时指定,然后在回调函数中处理方法调用的结果。
在ZK中,几乎为每个方法都提供了异步调用的版本,如getData方法,其函数原型如下所示:

void getData(String path, boolean watch, DataCallback cb, Object ctx);
其中:
DataCallback为提供回调函数的类,
ctx为回调函数需要的参数

示例代码如下:

  1. Children2Callback cb = new Children2Callback() {  
  2.             @Override  
  3.             public void processResult(int rc, String path, Object ctx,  
  4.                     List<String> children, Stat stat) {  
  5.                 for (String s : children) {  
  6.                     System.out.println("----->" + s);  
  7.                 }  
  8.                 System.out.println(ctx);    //输出:helloworld   
  9.             }  
  10.         };  
  11.           
  12.         zk.getChildren(path, true, cb, "helloworld");  

相信通过上面的学习一定能够熟悉ZK客户端的编程思路。

linux
相关资讯       ZooKeeper 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款