title: [大数据] zookeeper JAVA API 使用
tags:
- zookeeper
- 大数据
- 分布式
categories:
- 大数据
date: 2017-07-10 18:57:38
description: [大数据] zookeeper JAVA API 使用
1.基本使用
org.apache.zookeeper.Zookeeper
是客户端入口主类,负责建立与server的会话
它提供了表 1 所示几类主要方法 :
功能 | 描述 |
---|---|
create | 在本地目录树中创建一个节点 |
delete | 删除一个节点 |
exists | 测试本地是否存在目标节点 |
get/set data | 从目标节点上读取?/?写数据 |
get/set ACL | 获取?/?设置目标节点访问控制列表信息 |
get children | 检索一个子节点上的列表 |
sync | 等待要被传送的数据 |
表 1 : ZooKeeper API 描述
2.demo增删改查
package bigdata03.zk;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by 57871 on 2018/6/20.
*/
public class SimpleZK {
private static final String connectString = "bigdata01.com:2181,bigdata02.com:2181,bigdata03.com:2181";
private static final int sessionTimeout = 2000;
ZooKeeper zkClient = null;
@Before
public void init() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
//接受到监听事件的处理步骤
System.out.println(event.getType() + "--->"+event.getPath());
try {
List<String> children = zkClient.getChildren("/",true);
for(String child : children){
System.out.println( child );
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
*数据添加
* @throws Exception
*/
@Test
public void testCreate() throws Exception {
//参数1 路径 para2 内容 para3 权限 param4
zkClient.create("/idea","hello zk".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
/**
* 判断是否存在Znode
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void isExist() throws KeeperException, InterruptedException {
Stat stat = zkClient.exists("/idea", false);
System.out.println(stat != null ? "exist" : "not exist");
}
/**
* 判断Znode下的子节点
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/",true);
for(String child : children){
System.out.println( child );
}
}
/**
* 获得Znode的数据信息
* @throws KeeperException
* @throws InterruptedException
* @throws UnsupportedEncodingException
*/
@Test
public void getData() throws KeeperException, InterruptedException, UnsupportedEncodingException {
byte[] data = zkClient.getData("/idea", false, null);
System.out.println(new String(data,"utf-8"));
}
/**
* 修改Znode的数据信息
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void setData() throws KeeperException, InterruptedException {
Stat stat = zkClient.setData("/idea", "hellowordzk2".getBytes(), -1);
}
@Test
public void deleteData() throws KeeperException, InterruptedException {
zkClient.delete("/idea",-1);
}
}