pom.xml配置zookeeper

  1. <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
  2. <dependency>
  3. <groupId>org.apache.zookeeper</groupId>
  4. <artifactId>zookeeper</artifactId>
  5. <version>3.4.14</version>
  6. </dependency>

创建create

  1. String result = zk.create("/test_node",
  2. "test".getBytes(),
  3. ZooDefs.Ids.OPEN_ACL_UNSAFE,
  4. CreateMode.PERSISTENT);

异步

  1. class CreateCallBack implements AsyncCallback.StringCallback{
  2. public void processResult(int rc, String path, Object ctx, String name) {
  3. System.out.println("创建节点: " + path);
  4. System.out.println((String)ctx);
  5. }
  6. }
  1. String ctx = "{'create':'success'}";
  2. zk.create("/asyn_node",
  3. "test".getBytes(),
  4. ZooDefs.Ids.OPEN_ACL_UNSAFE,
  5. CreateMode.PERSISTENT,
  6. new CreateCallBack(),
  7. ctx
  8. );

修改节点数据

  1. zk.setData("/test_node","update_data".getBytes(),0);

删除

  1. zk.delete("/test_node",1);

ACL

  1. String writerId = DigestAuthenticationProvider.generateDigest("writer:123456");
  2. String readerId = DigestAuthenticationProvider.generateDigest("reader:654321");
  3. Id wId = new Id("digest", writerId);
  4. Id rId = new Id("digest", readerId);
  5. List<ACL> aclList = new ArrayList<ACL>();
  6. aclList.add(new ACL(ZooDefs.Perms.ALL, wId));
  7. aclList.add(new ACL(ZooDefs.Perms.READ, rId));
  8. zk.create("/acl_node", "node".getBytes(), aclList, CreateMode.PERSISTENT);
  1. zk.addAuthInfo("digest","writer:123456".getBytes());
  2. zk.create("/acl_node/digest_node","digest_node".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

客户端Curator

zookeeper原生api的不足之处
超时重连,不支持自动,需要手动重连
Watch注册一次会失效
不支持递归创建节点

  1. <dependency>
  2. <groupId>org.apache.curator</groupId>
  3. <artifactId>curator-recipes</artifactId>
  4. <version>4.2.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.curator</groupId>
  8. <artifactId>curator-framework</artifactId>
  9. <version>4.2.0</version>
  10. </dependency>
  1. CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
  2. .sessionTimeoutMs(15000)
  3. .retryPolicy(new RetryNTimes(3,5000)).
  4. namespace("namespace").build();
  5. client.start();
  6. try {
  7. client.create().creatingParentsIfNeeded().
  8. withMode(CreateMode.PERSISTENT).
  9. withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath("/super/test","testdata".getBytes());
  10. }catch (Exception e){
  11. e.printStackTrace();
  12. }