设为首页 收藏本站
查看: 1151|回复: 0

[经验分享] Java实现与ZooKeeper的连接

[复制链接]

尚未签到

发表于 2015-11-22 08:29:04 | 显示全部楼层 |阅读模式
序言
  续上一篇的 ZooKeeper安装运行  这里采用ZooKeeper的Java API进行连接。
  
Java实现
  新建一个类实现接口Watcher. 是指:
This interface specifies the public interface an event handler class must implement. A ZooKeeper client will get various events from the ZooKeepr server it connects to. An application using such a client handles these events by registering a callback object with the client. The callback object is expected to be an instance of a class that implements Watcher interface.

/**
* AbstractZooKeeper.java
* 版权所有(C) 2013
* 创建:cuiran 2013-01-16 14:59:44
*/
package com.zoo.demo;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;

/**
* TODO
* @author cuiran
* @version TODO
*/
public class AbstractZooKeeper implements Watcher {
private static Log log = LogFactory.getLog(AbstractZooKeeper.class.getName());
//缓存时间
private static final int SESSION_TIME   = 2000;   
protected ZooKeeper zooKeeper;
protected CountDownLatch countDownLatch=new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException{   
zooKeeper = new ZooKeeper(hosts,SESSION_TIME,this);   
countDownLatch.await();   
}   
/* (non-Javadoc)
* @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent)
*/
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
if(event.getState()==KeeperState.SyncConnected){
countDownLatch.countDown();
}
}
public void close() throws InterruptedException{   
zooKeeper.close();   
}  
}
然后写一些操作和main方法
/**
* ZooKeeperOperator.java
* 版权所有(C) 2013
* 创建:cuiran 2013-01-16 15:03:40
*/
package com.zoo.demo;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
/**
* TODO
* @author cuiran
* @version TODO
*/
public class ZooKeeperOperator extends AbstractZooKeeper {
private static Log log = LogFactory.getLog(ZooKeeperOperator.class.getName());
/**
*
*<b>function:</b>创建持久态的znode,比支持多层创建.比如在创建/parent/child的情况下,无/parent.无法通过
*@author cuiran
*@createDate 2013-01-16 15:08:38
*@param path
*@param data
*@throws KeeperException
*@throws InterruptedException
*/
public void create(String path,byte[] data)throws KeeperException, InterruptedException{
/**
* 此处采用的是CreateMode是PERSISTENT  表示The znode will not be automatically deleted upon client's disconnect.
* EPHEMERAL 表示The znode will be deleted upon the client's disconnect.
*/
this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
/**
*
*<b>function:</b>获取节点信息
*@author cuiran
*@createDate 2013-01-16 15:17:22
*@param path
*@throws KeeperException
*@throws InterruptedException
*/
public void getChild(String path) throws KeeperException, InterruptedException{   
try{
List<String> list=this.zooKeeper.getChildren(path, false);
if(list.isEmpty()){
log.debug(path+&quot;中没有节点&quot;);
}else{
log.debug(path+&quot;中存在节点&quot;);
for(String child:list){
log.debug(&quot;节点为:&quot;+child);
}
}
}catch (KeeperException.NoNodeException e) {
// TODO: handle exception
throw e;   
}
}
public byte[] getData(String path) throws KeeperException, InterruptedException {   
return  this.zooKeeper.getData(path, false,null);   
}  
public static void main(String[] args) {
try {   
ZooKeeperOperator zkoperator             = new ZooKeeperOperator();   
zkoperator.connect(&quot;192.168.0.138&quot;);
byte[] data = new byte[]{'a','b','c','d'};   
//            zkoperator.create(&quot;/root&quot;,null);   
//            System.out.println(Arrays.toString(zkoperator.getData(&quot;/root&quot;)));   
//               
//            zkoperator.create(&quot;/root/child1&quot;,data);   
//            System.out.println(Arrays.toString(zkoperator.getData(&quot;/root/child1&quot;)));   
//               
//            zkoperator.create(&quot;/root/child2&quot;,data);   
//            System.out.println(Arrays.toString(zkoperator.getData(&quot;/root/child2&quot;)));   
String zktest=&quot;ZooKeeper的Java API测试&quot;;
zkoperator.create(&quot;/root/child3&quot;, zktest.getBytes());
log.debug(&quot;获取设置的信息:&quot;+new String(zkoperator.getData(&quot;/root/child3&quot;)));
System.out.println(&quot;节点孩子信息:&quot;);   
zkoperator.getChild(&quot;/root&quot;);   
zkoperator.close();   

} catch (Exception e) {   
e.printStackTrace();   
}   
}
}

最后运行结果:

2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Documents and Settings\Administrator
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=D:\workspace\stormdemo1
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=192.168.0.138 sessionTimeout=2000 watcher=com.zoo.demo.ZooKeeperOperator@ca8327
2013-01-16 15:26:04:INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server /192.168.0.138:2181
2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 192.168.0.138/192.168.0.138:2181, initiating session
2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 192.168.0.138/192.168.0.138:2181, sessionid = 0x13c3c5224cc0003, negotiated timeout = 4000
2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 获取设置的信息:ZooKeeper的Java API测试
节点孩子信息:
2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - /root中存在节点
2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child1
2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child3
2013-01-16 15:26:13:DEBUG com.zoo.demo.ZooKeeperOperator - 节点为:child2
2013-01-16 15:26:13:INFO org.apache.zookeeper.ZooKeeper - Session: 0x13c3c5224cc0003 closed
2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - EventThread shut down


DSC0000.jpg
  
  针对出现的中文乱码看采用下面的处理即可:
   String zktest=&quot;ZooKeeper的Java API测试&quot;;
zkoperator.create(&quot;/root/child5&quot;, zktest.getBytes(&quot;utf-8&quot;));
log.debug(&quot;获取设置的信息:&quot;+new String(zkoperator.getData(&quot;/root/child5&quot;),&quot;utf-8&quot;));
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-141978-1-1.html 上篇帖子: Curator源码解析(四)ZooKeeper存在的连接问题 下篇帖子: ZooKeeper示例 分布式锁思路及示例代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表