编程
Zookeeper
接口难以使用,在连接zk超时,不支持自动重连;Watch注册一次会失效,需要反复注册;不支持递归创建节点,需要手动序列化
1 2 3 4 5
| <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> </dependency>
|
方法 |
描述 |
connect |
连接到ZooKeeper集合 |
create |
创建znode |
exists |
检查znode是否存在及其信息 |
getData |
从特定的znode获取数据 |
setData |
在特定的znode中设置数据 |
getChildren |
获取特定znode中的所有子节点 |
delete |
删除特定的znode及其所有子项 |
close |
关闭连接 |
Zkclient
基于原生API改造,比原生API用起来更称手
1 2 3 4 5
| <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package learn.zk;
import java.io.UnsupportedEncodingException;
import org.I0Itec.zkclient.exception.ZkMarshallingError; import org.I0Itec.zkclient.serialize.ZkSerializer;
public class MyZkSerializer implements ZkSerializer {
public byte[] serialize(Object data) throws ZkMarshallingError { String d = (String) data; try { return d.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
public Object deserialize(byte[] bytes) throws ZkMarshallingError { try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package learn.zk;
import java.util.List;
import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher.Event.KeeperState;
public class ZkClientDemo { public static void main(String[] args) { ZkClient client = new ZkClient("localhost:2181"); client.setZkSerializer(new MyZkSerializer()); client.create("/zk/app6", "123", CreateMode.PERSISTENT);
client.subscribeChildChanges("/zk/app6", new IZkChildListener() { public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { System.out.println(parentPath+"子节点发生变化:"+currentChilds); } });
client.subscribeDataChanges("/zk/app6", new IZkDataListener() { public void handleDataDeleted(String dataPath) throws Exception { System.out.println(dataPath + "节点被删除"); }
public void handleDataChange(String dataPath, Object data) throws Exception { System.out.println(dataPath + "发生变化:"+data); } });
try { Thread.currentThread().join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
|
Curator
Curator Apache 的开源项目
解决Watch注册一次就会失效的问题
提供的 API 更加简单易用
提供更多解决方案并且实现简单,例如:分布式锁
提供常用的ZooKeeper工具类
编程风格更舒服
工具
ZooInspector
1 2 3 4 5 6
| https://issues.apache.org/jira/secure/attachment/12436620/ZooInspector.zip
java -jar zookeeper-dev-ZooInspector.jar
|