Java操作ZooKeeper对象
1.使用Eclipse工具创建一个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>com.sl</groupId>
<artifactId>zookeeper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>zookeeper</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--zk-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
<!--zkclient-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.Java操作ZooKeeper对象
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ZooKeeperTest {
/**会话超时时间,设置与系统默认时间一致*/
private final int SESSION_TIMEOUT = 30000;
//创建ZooKeeper实例
ZooKeeper zk;
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
System.out.println(event.toString());
}
};
//初始化ZooKeeper实例
@Before
public void before() throws IOException {
zk = new ZooKeeper("192.168.0.200:2181", SESSION_TIMEOUT, watcher);
}
@After
public void after() throws InterruptedException {
zk.close();
}
@Test
public void create() throws KeeperException, InterruptedException {
//在创建节点的时候,需要提供节点的名称、数据、权限以及节点类型
System.out.println("1.创建ZooKeeper节点(znode:zoo2,数据:myData2,权限:OPEN_ACL_UNSAFE,节点类型:Persistent)");
zk.create("/zoo2", "myData2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getData() throws KeeperException, InterruptedException {
System.out.println("2.查看是否创建成功:");
System.out.println(new String(zk.getData("/zoo2", false, null)));
}
@Test
public void setData() throws KeeperException, InterruptedException {
System.out.println("3.修改节点数据:");
zk.setData("/zoo2", "xiugai1234".getBytes(), -1);
}
@Test
public void getSetData() throws KeeperException, InterruptedException {
System.out.println("4.查看是否修改成功:");
System.out.println(new String(zk.getData("/zoo2", false, null)));
}
@Test
public void delete() throws InterruptedException, KeeperException {
System.out.println("5.删除节点");
zk.delete("/zoo2", -1);
}
@Test
public void getStat() throws KeeperException, InterruptedException {
//使用 exists函数时,如果节点不存在将返回一个nul值
System.out.println("6.查看节点是否被删除:");
System.out.println("节点状态:["+zk.exists("/zoo2", false)+"]");
}
}
3.代码优化
zk的优点之一,就是高可用性,上面的代码连接的是单台zk server,如果这台server挂了,自然代码就会出错,事实上zk的API考虑到了这一点,把连接代码改成下面这样:
//初始化ZooKeeper实例
@Before
public void before() throws IOException {
zk = new ZooKeeper("192.168.0.200:2181,192.168.0.200:2182,192.168.0.200:2183", SESSION_TIMEOUT, watcher);
}
即:IP1:port1,IP2:port2,IP3:port3… 用这种方式连接集群就行了,只要有超过半数的zk server还活着,应用一般就没问题。但是也有一种极罕见的情况,比如这行代码执行时,刚初始化完成,正准备连接IP1时,因为网络故障IP1对应的server挂了,仍然会报错(此时,zk还来不及选出新leader),这个问题详见:http://segmentfault.com/q/1010000002506725/a-1020000002507402,参考该文的做法,改成:
import java.util.concurrent.TimeUnit;
//初始化ZooKeeper实例
@Before
public void before() throws IOException {
zk = new ZooKeeper("192.168.0.200:2181,192.168.0.200:2182,192.168.0.200:2183", SESSION_TIMEOUT, watcher);
if (!zk.getState().equals(ZooKeeper.States.CONNECTED)) {
while (true) {
if (zk.getState().equals(ZooKeeper.States.CONNECTED)) {
break;
}
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
这样写代码有些冗长,可以使用开源的zkClient,官方地址: https://github.com/sgroschupf/zkclient,使用方法很简单:
pom.xml配置
<!--zkclient-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
使用:
@Test
public static void zkClientTest() {
ZkClient zkClient = new ZkClient("192.168.0.200:2181,192.168.0.200:2182,192.168.0.200:2183");
String node2 = "/app2";
if (!zkClient.exists(node2)) {
zkClient.createPersistent(node2, "hello zk");
}
System.out.println(zkClient.readData(node2));
zkClient.delete(node2);
System.out.println(zkClient.exists(node2));
}
本文参考:
http://blog.youkuaiyun.com/shatelang/article/details/7596007
http://blog.youkuaiyun.com/huwei2003/article/details/49101269