ZooKeeperConnection.java 类处理与zookeeper建立链接。主要使用org.apache.zookeeper.ZooKeeper类。
public class ZooKeeperConnection
{
// declare zookeeper instance to access ZooKeeper ensemble
private ZooKeeper zoo;
final CountDownLatch connectedSignal = new CountDownLatch(1);
private static final String defaultHost ="192.168.1.68:2181";
// Method to connect zookeeper ensemble.
public ZooKeeper connect() throws IOException, InterruptedException
{
zoo = new ZooKeeper(defaultHost, 5000, new Watcher()
{
public void process(WatchedEvent we)
{
System.out.println(we);
if (we.getState() == KeeperState.SyncConnected)
{
connectedSignal.countDown();
}
}
});
connectedSignal.await();
return zoo;
}
// Method to disconnect from zookeeper server
public void close() throws InterruptedException
{
zoo.close();
}
public static void main(String[] args) throws IOException, InterruptedException
{
new ZooKeeperConnection().connect();
}
}
在zookeeper类中主要启动SendThread 线程和EventThread 线程。
This class services the outgoing request queue and generates the heart beats. It also spawns the ReadThread.
SendThread线程主要处理IO读写事件 和心跳包。
EventThread 主要处理事件回调,为业务逻辑线程。
ZKCreate.java 通过该类来剖析zookeeper 中客户端流程。
public class ZKCreate
{
// create static instance for zookeeper class.
private static ZooKeeper zk;
// create static instance for ZooKeeperConnection class.
private static ZooKeeperConnection conn;
// Method to create znode in zookeeper ensemble
public static String create(String path, byte[] data) throws KeeperException, InterruptedException
{
return zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
// Method to create znode in zookeeper ensemble
public static void create(String path, byte[] data, StringCallback callback, Object obj) throws KeeperException, InterruptedException
{
zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, callback, obj);
}
public static void main(String[] args) throws KeeperException, InterruptedException
{
// znode path
String path = "/MyFirstZnode"; // Assign path to znode
// data in byte array
byte[] data = "My first zookeeper app".getBytes(); // Declare data
try
{
conn = new ZooKeeperConnection();
zk = conn.connect();
String createPath = create(path, data); // Create the data to the
// specified path
System.out.println("createPath:" + createPath);
conn.close();
}
catch (Exception e)
{
System.out.println(e.getMessage()); // Catch error message
}
}
}
当zookeeper 调用create()方法时,来创建一个节点。
public String create(final String path, byte data[], List<ACL> acl,
CreateMode createMode)
throws KeeperException, InterruptedException
{
final String clientPath = path;
PathUtils.validatePath(clientPath, createMode.isSequential());
final String serverPath = prependChroot(clientPath);
//创建一个请求消息头
RequestHeader h = new RequestHeader();
//设置消息类型
h.setType(ZooDefs.OpCode.create);
//创建消息实体
CreateRequest request = new CreateRequest();
//创建消息返回实体
CreateResponse response &#