zookeeper的三个客户端框架
原生ZooKeeper
原生ZooKeeper的watcher只能用一次
public class ZookeeperClientTest {
public static void main(String[] args) throws IOException {
// 默认的watcher
ZooKeeper client = new ZooKeeper("localhost:2181", 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("连接的时候"+event);
}
});
Stat Stat = new Stat();// 状态
try {
String s = new String(client.getData("/name", new Watcher() {
@Override
public void process(WatchedEvent event) {
// 监听器,zookeeper原生的监听器只会触发一次
if(event.getType().equals(Event.EventType.NodeDataChanged)){
// 节点值改变
System.out.println("数据发生了改变");
}
}
},Stat));
} catch (Exception e) {
e.printStackTrace();
}
/*client.getData("/name", true, new AsyncCallback.DataCallback() {
@Override
public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
System.out.println(rc);
System.out.println(path);
System.out.println("只要连接就会有回调");
String s = new String(data);
System.out.println(s);
}
},null);*/
System.in.read();
}
}
zkclient
需要zkclient-0.3.jar
/**
* 需要zkclient
*/
public class ZkClientTest {
public static void main(String[] args)throws IOException{
// 客户端连接配置
ZkClient zkClient = new ZkClient("localhost:2181",1000,1000,
new SerializableSerializer());
// 创建永久节点
zkClient.createPersistent("/name1",1);
// 监听,可以解决zookeeper原生的监听器只触发一次的问题
zkClient.subscribeDataChanges("/name1", new IZkDataListener() {
@Override
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("数据改变了");
}
@Override
public void handleDataDeleted(String s) throws Exception {
System.out.println("节点删除了");
}
});
System.in.read();
}
}
curator
用的比较多的一种,封装的功能很多
需要curator-client-4.0.1.jar、curator-framework-4.0.1.jar、curator-recipes-4.0.1.jar
public class CuratorClient {
public static void main(String[] args)throws Exception{
CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181",
new RetryNTimes(3,1000));
client.start();
/**
* PERSISTENT:持久化
* PERSISTENT_SEQUENTIAL:持久化并且带序列号
* EPHEMERAL:临时
* EPHEMERAL_SEQUENTIAL:临时并且带序列号
*/
client.create().withMode(CreateMode.PERSISTENT).forPath("/name","7".getBytes());
NodeCache nodeCache = new NodeCache(client,"/name");
// 参数:false默认的入参,创建节点时就出发;true创建节点时不触发
nodeCache.start(true);
// 监听,可以解决zookeeper原生的监听器只触发一次的问题
nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println("数据发生了改变");
}
});
/*client.getData().usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent event) {
// 只会触发一次
System.out.println("zookeeper原生的Watcher");
}
}).forPath("/name");*/
System.in.read();
}
}