一、向Zookeeper中注册内容
新建项目ZookeeperClient
1 创建/demo
使用zookeeper的客户端命令工具创建/demo
./zkCli.sh create /demos
2 添加依赖
<dependencies> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.5.5</version> </dependency> </dependencies>
3 编写代码
创建类com.msb.MyApp。
ZooDefs.Ids.OPEN_ACL_UNSAFE 表示权限。
CreateMode.PERSISTENT_SEQUENTIAL 永久存储,文件内容编号递增。
public static void main(String [] args){ try { ZooKeeper zookeeper = new ZooKeeper("192.168.32.128:2181", 10000, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { System.out.println("获取连接"); } }); String content = zookeeper.create("/demo/nn", "content".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); System.out.println("content"+content); } catch (IOException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
4 查看上传数据
ls -R / :查看列表
get /demo/nn0000000002 :查看内容
二、 从zookeeper中发现内容
在原有项目中新建一个类,类中编写主方法。
public static void main(String[] args) { try { ZooKeeper zookeeper = new ZooKeeper("192.168.32.128:2181", 10000, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { System.out.println("获取连接"); } }); //获取列表 List<String> list = zookeeper.getChildren("/demo", false); for (String child : list) { byte[] result = zookeeper.getData("/demo/" + child, false, null); System.out.println(new String(result)); } } catch (IOException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }