zookeeper使用实例
时间: 2023-09-09 10:14:11 浏览: 109
以下是一个使用ZooKeeper的Java示例:
```java
import org.apache.zookeeper.*;
public class ZooKeeperExample implements Watcher {
private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
private static final int SESSION_TIMEOUT = 3000;
private ZooKeeper zooKeeper;
public static void main(String[] args) {
try {
ZooKeeperExample example = new ZooKeeperExample();
example.connect();
example.createNode("/myNode", "myNodeData");
String data = example.getData("/myNode");
System.out.println("Data: " + data);
example.deleteNode("/myNode");
example.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void connect() throws Exception {
zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, this);
}
public void createNode(String path, String data) throws Exception {
zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public String getData(String path) throws Exception {
byte[] data = zooKeeper.getData(path, false, null);
return new String(data);
}
public void deleteNode(String path) throws Exception {
zooKeeper.delete(path, -1);
}
public void close() throws Exception {
zooKeeper.close();
}
@Override
public void process(WatchedEvent event) {
// Do nothing
}
}
```
这个实例创建了一个ZooKeeper连接,然后它创建了一个节点,获取节点的数据,删除节点,最后关闭连接。关键点在于使用ZooKeeper类来连接到ZooKeeper服务并执行操作。此外,还需要实现Watcher接口,以便处理ZooKeeper事件。
阅读全文