ZKUtils.java

package test;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class ZKUtils {
public static ZooKeeper openZk() throws IOException, InterruptedException {
//连接zookeeper成功的标志
final CountDownLatch connectedSignal = new CountDownLatch(1); ZooKeeper zk = new ZooKeeper(Test.connectString, Test.sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if(KeeperState.SyncConnected.equals(event.getState())) {
//连接成功则打开当前进程
connectedSignal.countDown();
}
}
}); //对CountDownLatch对象调用await()方法后,当前线程会堵塞等待,直到对象的计数器为0(调用对象的countDown()方法减1)
//堵塞当前进程
connectedSignal.await();
return zk;
}
}

  

Test.java

package test;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
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.ZooDefs.Perms;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
public class Test {
public static final String connectString = "hadoop1:2181";
public static final int sessionTimeout = 5000;
public static void main(String[] args) throws Exception {
//创建path
// createZnode("/b"); //列出子znode
// listChildren("/"); // delete("/b"); // deleteAsynchronous("/b");
// watch(); //强制客户端连接的服务区跟领导者进行同步,以更新指定path的状态,只能是异步调用
sync(); /*
* 验证
*/
// auth1();
// auth2();
}
/**
* 创建znode
* @param path
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void createZnode(String path) throws IOException, InterruptedException,
KeeperException {
ZooKeeper zk = ZKUtils.openZk();
String createdPath = zk.create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("创建" + createdPath + "成功"); // 创建znode, 数据是hello, ACL(访问控制列表)是完全放开的列表, 短暂类型的znode(session断开后,znode将被zookeeper服务器删除)
// String createdPath = zk.create(path, "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// 这里打印的是
// System.out.println(createdPath);
// 顺序的短暂znode
// createdPath = zk.create(path, "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
// 这里打印的是path000000000N, 路径名+10位的序列号
// System.out.println(createdPath);
} /**
* 列出子znode
* @param parent
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void listChildren(String parent) throws IOException, InterruptedException,
KeeperException {
ZooKeeper zk = ZKUtils.openZk(); Stat state = zk.exists(parent, false);
if(state == null) {
return;
} List<String> children = zk.getChildren(parent, false);
for (String child : children) {
System.out.println(child);
}
} /**
* 删除znode及其子znode
* @param path
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void delete(String path) throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = ZKUtils.openZk(); Stat state = zk.exists(path, false);
if(state == null) {
return;
} System.out.println(state.getVersion()); List<String> children = zk.getChildren(path, false);
for (String child : children) {
delete(path + "/" + child);
} //需要指定path和version, version为-1则取消版本号验证
zk.delete(path, -1);
} /**
* 异步操作
* zookeeper同时提供同步、异步两个版本的API,业务对读取效率没影响的情况下选择哪个方式都可以.
* @param path
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void deleteAsynchronous(String path) throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = ZKUtils.openZk(); Stat state = zk.exists(path, false);
if(state == null) {
return;
} List<String> children = zk.getChildren(path, false);
for (String child : children) {
delete(path + "/" + child);
} //需要指定path和version, version为-1则取消版本号验证
// zk.delete(path, -1);
zk.delete(path, -1, new VoidCallback() {
@Override
public void processResult(int rc, String path, Object ctx) {
System.out.println("异步删除操作执行完毕 , rc: " + rc + ", path: " + path);
}
}, null); //等待一会, 否则主线程直接结束了就看不到异步线程的输出结果了
Thread.sleep(2000);
} /**
* 监听事件
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void watch() throws IOException, InterruptedException, KeeperException {
final CountDownLatch singal = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper("hadoop1:2181", 5000, new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("接受到了一个事件:" + event);
if(Watcher.Event.KeeperState.SyncConnected.equals(event.getState())) {
singal.countDown();
}
}
});
singal.await();
//exists、getData、getChildren操作可以设置监控 //判断"/b"是否存在并对其进行监控, 使用创建zookeeper时的watcher处理
zk.exists("/b", true); //使用指定的watcher处理
// zk.exists("/b", new Watcher()); Thread.sleep(Long.MAX_VALUE); } /**
* 强制客户端连接的服务器跟领导者进行同步,以更新指定znode的状态
* 只能异步调用
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void sync() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = ZKUtils.openZk();
zk.sync("/a", new VoidCallback(){
@Override
public void processResult(int rc, String path, Object ctx) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("同步完毕");
} }, null); System.out.println("here"); Stat stat = zk.exists("/a", false);
byte[] data = zk.getData("/a", false, stat);
System.out.println("data: " + new String(data)); Thread.sleep(5000);
} /**
* 使用自定义ACL创建znode
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
* @throws NoSuchAlgorithmException
*/
private static void auth1() throws IOException, InterruptedException, KeeperException, NoSuchAlgorithmException { List<ACL> acls = new ArrayList<ACL>();
//用户名密码验证方式
Id id = new Id("digest", DigestAuthenticationProvider.generateDigest("lisg:123456"));
acls.add(new ACL(Perms.READ, id)); ZooKeeper zk = ZKUtils.openZk();
zk.create("/c", "test".getBytes(), acls, CreateMode.PERSISTENT);
} /**
* ACL验证
* @throws IOException
* @throws InterruptedException
* @throws KeeperException
*/
private static void auth2() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = ZKUtils.openZk(); Stat stat = zk.exists("/c", false);
if(stat == null) {
return;
} List<ACL> cacls = zk.getACL("/c", stat);
System.out.println("/c的ACL列表是:" + cacls); //KeeperErrorCode = NoAuth for /c 异常
zk.addAuthInfo("digest", "lisg:123456".getBytes());
byte[] data = zk.getData("/c", false, stat);
System.out.println("data: " + new String(data));
}
}

  

zookeeper - java操作的更多相关文章

  1. Java操作zookeeper

    Java操作zookeeper总共有三种方式: 1.原生的Java API 2.zkclient 3.curator 第一种实现代码: pom.xml <dependency> <g ...

  2. java 操作zookeeper

    java 操作zookeeper(一) 首先要使用java操作zookeeper,zookeeper的javaclient 使我们更轻松的去对zookeeper进行各种操作,我们引入zookeeper ...

  3. zookeeper(三):java操作zookeeper

    引入jar包 首先要使用java操作zookeeper,zookeeper的javaclient 使我们更轻松的去对zookeeper进行各种操作,我们引入zookeeper-3.4.5.jar 和 ...

  4. Hbase深入学习(六) Java操作HBase

    Hbase深入学习(六) ―― Java操作HBase 本文讲述如何用hbase shell命令和hbase java api对hbase服务器进行操作. 先看以下读取一行记录hbase是如何进行工作 ...

  5. Java操作hbase总结

    用过以后,总得写个总结,不然,就忘喽. 一.寻找操作的jar包. java操作hbase,首先要考虑到使用hbase的jar包. 因为咱装的是CDH5,比较方便,使用SecureCRT工具,远程连接到 ...

  6. 9. 使用ZooKeeper Java API编程

    ZooKeeper是用Java开发的,3.4.6版本的Java API文档可以在http://zookeeper.apache.org/doc/r3.4.6/api/index.html上找到. Ti ...

  7. zookeeper客户端操作

    ZooKeeper客户端 zkCli.sh 节点的增删改查 在 bin 目录下的  zkCli.sh  就是ZooKeeper客户端 ./zkCli.sh -timeout 5000  -server ...

  8. zookeeperCli和Java操作zookeeperAPI

    推荐一个zookeeper可视化工具:zktools.exe eclipse集成的工具: http://www.massedynamic.org/eclipse/updates/ 1.zkCli客户端 ...

  9. java操作Hbase实例

    所用HBase版本为1.1.2,hadoop版本为2.4 /* * 创建一个students表,并进行相关操作 */ import java.io.IOException; import java.u ...

随机推荐

  1. (转)Python标准库02 时间与日期 (time, datetime包)

    原文:http://www.cnblogs.com/vamei/archive/2012/09/03/2669426.html https://www.liaoxuefeng.com/wiki/001 ...

  2. python代码位置引发的错误

    觉得python对代码位置的要求简直是变态,缩进引发的错误我以前在博客里讲过了,如果不懂可以看看我以前的博客,今天又遇到了一个代码位置所引发的错误,现在给大家分享一下: 我想要打印出来一个5*5的实心 ...

  3. jquery插件开发的demo

    (function ($) { $.fn.extend({ "highLight": function (options) { //检测用户传进来的参数是否合法 if (!isVa ...

  4. elasticsearch版本不同,批量查询也不相同

    网上搜到批量查询可以通过TransportClient实现,但官方推荐使用RestHighLevelClient实现 注意: We plan on deprecating the TransportC ...

  5. Django 多表查询

    多表查询是模型层的重要功能之一, Django提供了一套基于关联字段独特的解决方案. ForeignKey 来自Django官方文档的模型示例: from django.db import model ...

  6. hadoop学习笔记(十):MapReduce工作原理(重点)

    一.MapReduce完整运行流程 解析: 1 在客户端启动一个作业. 2 向JobTracker请求一个Job ID. 3 将运行作业所需要的资源文件复制到HDFS上,包括MapReduce程序打包 ...

  7. mysql replace语句

    语法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 REPLACE [LOW_PRIORITY | DELAYED]     [INTO] tbl_name     [ ...

  8. MVC初级教程(二)

    演示产品源码下载地址:http://www.jinhusns.com/Products/Download 

  9. insert into 语句的三种写法

    insert into 语句的三种写法 方式1. INSERT INTO t1(field1,field2) VALUES (v001,v002);            // 明确只插入一条Valu ...

  10. DBNull.Value 与null

    来源:http://blog.csdn.net/beautifulsarah/article/details/54691670 DBNull.Value,, 适用于向数据库的表中插入空值.而 null ...