1. Create
package com.demo;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
public class ZKDemo {
private static final String connectString = "";
private static final int sessionTimeout = 0;
private static Watcher watcher;
private static Boolean canBeReadOnly = false;
private static long sessionId;
private static byte[] sessionPasswd;
public static void main(String[] args) throws IOException {
ZooKeeper zooKeeper1 = new ZooKeeper(connectString,sessionTimeout,watcher);
ZooKeeper zooKeeper2 = new ZooKeeper(connectString,sessionTimeout,watcher,canBeReadOnly);
ZooKeeper zooKeeper3 = new ZooKeeper(connectString,sessionTimeout,watcher,sessionId,sessionPasswd);
ZooKeeper zooKeeper4 = new ZooKeeper(connectString,sessionTimeout,watcher,sessionId,sessionPasswd,canBeReadOnly);
}
}
The establishment of the session between the client and the server is an asynchronous process, that is,
-
After the initialization of the client is completed, it returns, and the connection is not really established at this time.
-
When the connection is actually established, the client will receive a time notification
2, ZK construction method parameter description
3. Create a session
package com.demo;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class ZKCreateSample implements Watcher{
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static final String connectString = "127.0.0.1:2181";
private static final int sessionTimeout = 6000;
public static void main(String[] args) throws IOException {
ZooKeeper zooKeeper = new ZooKeeper(connectString,sessionTimeout,new ZKCreateSample());
System.out.println("begin state = "+ zooKeeper.getState());
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("end state = "+zooKeeper.getState());
}
System.out.println("end state= "+zooKeeper.getState());
}
@Override
public void process(WatchedEvent event) {
System.out.println("receive watched event: "+ event);
if(Event.KeeperState.SyncConnected == event.getState()){
countDownLatch.countDown();
}
}
}
4. Create a node
-
String create(final String path, byte data[], List<ACL> acl,CreateMode createMode)
-
void create(final String path, byte data[], List<ACL> acl,CreateMode createMode, StringCallback cb, Object ctx) Create a node asynchronously
-
Whether it is synchronous or asynchronous above, recursive node creation is not supported
-
When the node exists, throw an exception NodeExistsException
1. zk create api parameter description
2. ACL when creating a node
- There are several pre-defined scheme modes through interface Ids
1. OPEN_ACL_UNSAFE : equivalent to world : anyone : cdrwa
2. CREATOR_ALL_ACL: equivalent to anth: username: password, but you need to add the corresponding user and password through Zookeeper's addAuthInfo
3. READ_ACL_UNSAFE: equivalent to world: anyone: r, that is, everyone has read permission
3. You can define your own, such as:
package com.demo;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import java.util.ArrayList;
import java.util.List;
public class ZKOPSample {
public static void main(String[] args) {
}
/**
* 添加digest权限
* @return
*/
public List<ACL> getDigestAcl() {
List<ACL> acls = new ArrayList<ACL>();
Id digestId = new Id("digest","javaclient2:CGf2ylBdcKMdCYuzd08lQfOPvN0=");
acls.add(new ACL(ZooDefs.Perms.ALL, digestId));
return acls;
}
}
5. Delete the node
package com.demo;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ZKOPSample {
private ZooKeeper zk = null;
public ZKOPSample(String connectString) {
try {
zk = new ZooKeeper(connectString, 1000, null);
} catch (IOException e) {
e.printStackTrace();
if (zk != null) {
try {
zk.close();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
ZKOPSample zks = new ZKOPSample("127.0.0.1:2181");
//zks.getDigestAcl();
// 所有人都可以访问的节点
// zks.testCreateNode("/javaclient/node3","java".getBytes(),
// ZooDefs.Ids.OPEN_ACL_UNSAFE);
// 同步删除节点
// zks.deleteNode("/javaclient/node1",0);
// 异步删除节点
// String ctx = "上下文测试对象";
// zks.deleteAsyncNode("/javaclient/node3",0,new DeleteAsyncCallback(),ctx);
// Thread.sleep(3000);
}
/**
* 同步删除节点
* @param path
* @param version
*/
public void deleteNode(String path,int version){
try {
zk.delete(path,version);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
/**
* 异步删除节点
*
* @param path
* @param version
* @param voidCallback
* @param ctx
*/
public void deleteAsyncNode(String path, int version, AsyncCallback.VoidCallback voidCallback, Object ctx){
zk.delete(path,version,voidCallback,ctx);
}
/**
* 创建节点
*
* @param path
* @param data
* @param acls
* @return
*/
public String testCreateNode(String path, byte[] data, List<ACL> acls) {
String res = "";
try {
// zk.addAuthInfo("auth", "javaclient1:111111".getBytes());
res = zk.create(path, data, acls, CreateMode.PERSISTENT);
System.out.println("创建节点" + res + "成功");
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
/**
* 添加digest权限
* @return
*/
public List<ACL> getDigestAcl() {
List<ACL> acls = new ArrayList<ACL>();
Id digestId = new Id("digest","javaclient2:CGf2ylBdcKMdCYuzd08lQfOPvN0=");
acls.add(new ACL(ZooDefs.Perms.ALL, digestId));
return acls;
}
public ZooKeeper getZk() {
return zk;
}
public void setZk(ZooKeeper zk) {
this.zk = zk;
}
}
Asynchronous delete callback method
package com.demo;
import org.apache.zookeeper.AsyncCallback;
/**
* 异步删除节点回调类
*/
public class DeleteAsyncCallback implements AsyncCallback.VoidCallback {
@Override
public void processResult(int rc, String path, Object ctx) {
System.out.println("执行回调方法");
System.out.println("rc: "+rc);
System.out.println("path: "+path);
System.out.println("ctx "+ ctx);
}
}