zookeeper实战2.docx
- 文档编号:11298433
- 上传时间:2023-02-26
- 格式:DOCX
- 页数:16
- 大小:1.24MB
zookeeper实战2.docx
《zookeeper实战2.docx》由会员分享,可在线阅读,更多相关《zookeeper实战2.docx(16页珍藏版)》请在冰豆网上搜索。
zookeeper实战2
Zookeeper第二周
一、Watcher的原理以及API实践
(API监听一次就会失效)
基于zookeeper的API,使用一个线程监测zookeeper集群节点的变化情况,具体代码如下:
importjava.io.IOException;
importjava.util.List;
importorg.apache.log4j.Logger;
importorg.apache.zookeeper.KeeperException;
importorg.apache.zookeeper.WatchedEvent;
importorg.apache.zookeeper.Watcher;
importorg.apache.zookeeper.Watcher.Event.EventType;
/**
*
*@authorhadoop
*
*/
publicclassZKNodeWatcherextendsAbstractZooKeeperimplementsRunnable{
privatestaticList
StringmonitorNode;
privatestaticLoggerLog=Logger.getLogger(ZKNodeWatcher.class);
publicZKNodeWatcher(StringmonitorNode){
super();
this.monitorNode=monitorNode;
try{
this.connect("master");
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
publicStringgetMonitorNode(){
returnmonitorNode;
}
publicvoidsetMonitorNode(StringmonitorNode){
this.monitorNode=monitorNode;
}
publicvoidrun(){
synchronized(this){
try{
monitorNodes(getWatcher());
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
Log.error(e);
}
}
}
publicWatchergetWatcher(){
returnnewWatcher(){
@Override
publicvoidprocess(WatchedEventevent){
//结点数据改变之前的结点列表
List
//主结点的数据发生改变时
if(event.getType()==EventType.NodeDataChanged){
try{
Log.info("节点数据发生变化:
"+event.getPath()+"-->数据变为"+newString(getData(event.getPath())));
}catch(Exceptione){
//TODOAuto-generatedcatchblock
Log.error(e);;
}
}
//节点被删除是触发
if(event.getType()==EventType.NodeDeleted){
Log.info("节点被删除:
"+event.getPath());
}
//节点新创建时触发
if(event.getType()==EventType.NodeCreated){
Log.info("新节点创建:
"+event.getPath());
}
//获取更新后的nodelist
try{
nodeList=zooKeeper.getChildren(event.getPath(),false);
}catch(Exceptione){
Log.error(e);
Log.info(event.getPath()+"hasnochild");
}
List
//增加结点
if(nodeListBefore.size() for(Stringstr: nodeListNow){ if(! nodeListBefore.contains(str)){ Log.info("新增加的节点是: "+event.getPath()+"/"+str); } } } } }; } publicvoidmonitorNodes(Watcherwc)throwsInterruptedException{ for(;;){ try{ zooKeeper.exists(getMonitorNode(),wc);//所要监控的主结点 }catch(Exceptione){ Log.error(e); } Thread.sleep(3000);// try{ nodeList=zooKeeper.getChildren(getMonitorNode(),wc); for(Stringchild: nodeList){ Log.info(getMonitorNode()+"的子节点有: "+child); } }catch(Exceptione){ Log.error(e); } Thread.sleep(3000); //对PATH下的每个结点都设置一个watcher if(null! =nodeList&&nodeList.size()>0){ for(StringnodeName: nodeList){ try{ zooKeeper.exists(getMonitorNode()+"/"+nodeName,wc); }catch(Exceptione){ Log.error(e); } } } } } /** * *获取节点数据 * */ publicbyte[]getData(Stringpath)throwsKeeperException,InterruptedException{ returnthis.zooKeeper.getData(path,false,null); } publicstaticvoidmain(String[]args){ newThread(newZKNodeWatcher("/node")).start(); } } importjava.io.IOException; importjava.util.concurrent.CountDownLatch; importorg.apache.log4j.Logger; importorg.apache.zookeeper.WatchedEvent; importorg.apache.zookeeper.Watcher; importorg.apache.zookeeper.Watcher.Event.KeeperState; importorg.apache.zookeeper.ZooKeeper; /** * *@authorhadoop * */ publicclassAbstractZooKeeperimplementsWatcher{ protectedLoggerlogger=Logger.getLogger(AbstractZooKeeper.class); //缓存时间 privatestaticfinalintSESSION_TIME=2000; protectedZooKeeperzooKeeper; protectedCountDownLatchcountDownLatch=newCountDownLatch (1); //连接zk集群 publicvoidconnect(Stringhosts)throwsIOException,InterruptedException{ zooKeeper=newZooKeeper(hosts,SESSION_TIME,this); countDownLatch.await(); } //zk处理 @Override publicvoidprocess(WatchedEventevent){ if(event.getState()==KeeperState.SyncConnected){ countDownLatch.countDown(); } System.out.println("已经触发了"+event.getType()+"事件! "); } //关闭集群 publicvoidclose()throwsInterruptedException{ zooKeeper.close(); } } 运行之后,客户端一直在监测zookeeper集群的节点情况 在另外客户端进行新建节点操作 API均能监测到节点变化信息 2、zookeeper的ACL实践 ØWorld模式 ØAuth模式 ØDigest模式 ØIP模式 ØSuper模式 由于使用super模式其用户名以及密码需要经过sha1和base64转码,利用以下的Java代码实现加密转码。 importjava.io.IOException; importjava.security.MessageDigest; importjava.security.NoSuchAlgorithmException; importorg.apache.zookeeper.KeeperException; /** * *@authorhadoop * */ publicclassSuperAcl{ publicstaticvoidmain(String[]args)throwsIOException,InterruptedException,KeeperException{ Stringpasswd="super: admin123"; System.out.println(generateDigest(passwd)); } staticpublicStringgenerateDigest(StringidPassword){ Stringparts[]=idPassword.split(": ",2); bytedigest[]=null; try{ digest=MessageDigest.getInstance("SHA1").digest(idPassword.getBytes()); }catch(NoSuchAlgorithmExceptione){ e.printStackTrace(); } returnparts[0]+": "+base64Encode(digest); } staticfinalprivateStringbase64Encode(byteb[]){ StringBuildersb=newStringBuilder(); for(inti=0;i intpad=0; intv=(b[i++]&0xff)<<16; if(i v|=(b[i++]&0xff)<<8; }else{ pad++; } if(i v|=(b[i++]&0xff); }else{ pad++; } sb.append(encode(v>>18)); sb.append(encode(v>>12)); if(pad<2){ sb.append(encode(v>>6)); }else{ sb.append('='); } if(pad<1){ sb.append(encode(v)); }else{ sb.append('='); } } returnsb.toString(); } staticfinalprivatecharencode(inti){ i&=0x3f; if(i<26){ return(char)('A'+i); } if(i<52){ return(char)('a'+i-26); } if(i<62){ return(char)('0'+i-52); } returni==62? '+': '/'; } } 修改Zookeeper的启动脚本zkServer.sh,在start附件(100行左右)加入以下配置: -Dzookeeper.DigestAuthenticationProvider.superDigest=super: /o7XEyClGiOcKnJmPVFVYU8AQdw= 重新启动Zookeeper服务: zkServer.shrestart 使用super: admin123连接Zookeeper服务器就可以对里面的节点任意妄为了。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- zookeeper 实战
![提示](https://static.bdocx.com/images/bang_tan.gif)