本篇,根据网上代码,整理了一个例子,Zookeeper的HelloWorld。
下面这个代码,还是比较简单的,核心类就是org.apache.zookeeper.ZooKeeper。
我比较喜欢这种"框架",把最核心的服务,就用少数的几个类或者接口,供开发者使用。
开发者,不用知道那么多代码和细节。
这也提示我们,写代码的时候,把对外服务和对内实现,分开,设计好。
package cn.fansunion.zookeeper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class ZooKeeperTest { private static final int TIME_OUT = 3000; private static final String HOST = "localhost:2181"; public static void main(String[] args) throws Exception{ ZooKeeper zookeeper = new ZooKeeper(HOST, TIME_OUT, null); System.out.println("=========创建节点==========="); if(zookeeper.exists("/test", false) == null) { zookeeper.create("/test", "znode1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } System.out.println("=============查看节点是否安装成功==============="); System.out.println(new String(zookeeper.getData("/test", false, null))); System.out.println("=========修改节点的数据=========="); String data = "zNode2"; zookeeper.setData("/test", data.getBytes(), -1); System.out.println("========查看修改的节点是否成功========="); System.out.println(new String(zookeeper.getData("/test", false, null))); System.out.println("=======删除节点=========="); zookeeper.delete("/test", -1); System.out.println("==========查看节点是否被删除============"); System.out.println("节点状态:" + zookeeper.exists("/test", false)); zookeeper.close(); } }
运行结果
log4j:WARN No appenders could be found for logger (org.apache.zookeeper.ZooKeeper).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
=========创建节点===========
=============查看节点是否安装成功===============
znode1
=========修改节点的数据==========
========查看修改的节点是否成功=========
zNode2
=======删除节点==========
==========查看节点是否被删除============
节点状态:null
以上代码,看不懂,根本没有关系。
懂了概念,知道了大致的API用法,后面就是深入学习。
Zookeeper怎么设计,API怎么用,怎么实现“分布式锁”。
有了良好的开端,上了道,就一步步提高了。
上次买了本Zookeeper的书,专门讲解Zookeeper的,还没来得及看。
最近看Android书籍,研究和运行代码。看Object-c和iOS,再写代码,太忙了。
Zookeeper的进一步深入学习,可能要再过一段时间了。
Maven配置
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.fansunion</groupId> <artifactId>ZookeeperDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source /> <target /> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>